2005-04-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / keygen.c
blob72c5e1e8ad806cc13f36f9859c9a9ef7239ade06
1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002,
3 * 2003, 2004 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 2 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, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <errno.h>
28 #include <assert.h>
30 #include "gpg.h"
31 #include "util.h"
32 #include "main.h"
33 #include "packet.h"
34 #include "cipher.h"
35 #include "ttyio.h"
36 #include "options.h"
37 #include "keydb.h"
38 #include "trustdb.h"
39 #include "status.h"
40 #include "i18n.h"
41 #include "call-agent.h"
44 #define MAX_PREFS 30
46 enum para_name {
47 pKEYTYPE,
48 pKEYLENGTH,
49 pKEYUSAGE,
50 pSUBKEYTYPE,
51 pSUBKEYLENGTH,
52 pSUBKEYUSAGE,
53 pAUTHKEYTYPE,
54 pNAMEREAL,
55 pNAMEEMAIL,
56 pNAMECOMMENT,
57 pPREFERENCES,
58 pREVOKER,
59 pUSERID,
60 pEXPIREDATE,
61 pKEYEXPIRE, /* in n seconds */
62 pSUBKEYEXPIRE, /* in n seconds */
63 pPASSPHRASE,
64 pPASSPHRASE_DEK,
65 pPASSPHRASE_S2K,
66 pSERIALNO
69 struct para_data_s {
70 struct para_data_s *next;
71 int lnr;
72 enum para_name key;
73 union {
74 DEK *dek;
75 STRING2KEY *s2k;
76 u32 expire;
77 unsigned int usage;
78 struct revocation_key revkey;
79 char value[1];
80 } u;
83 struct output_control_s {
84 int lnr;
85 int dryrun;
86 int use_files;
87 struct {
88 char *fname;
89 char *newfname;
90 iobuf_t stream;
91 armor_filter_context_t afx;
92 } pub;
93 struct {
94 char *fname;
95 char *newfname;
96 iobuf_t stream;
97 armor_filter_context_t afx;
98 } sec;
102 struct opaque_data_usage_and_pk {
103 unsigned int usage;
104 PKT_public_key *pk;
108 static int prefs_initialized = 0;
109 static byte sym_prefs[MAX_PREFS];
110 static int nsym_prefs;
111 static byte hash_prefs[MAX_PREFS];
112 static int nhash_prefs;
113 static byte zip_prefs[MAX_PREFS];
114 static int nzip_prefs;
115 static int mdc_available,ks_modify;
117 static void do_generate_keypair( struct para_data_s *para,
118 struct output_control_s *outctrl, int card);
119 static int write_keyblock( iobuf_t out, KBNODE node );
120 static int gen_card_key (int algo, int keyno, KBNODE pub_root, KBNODE sec_root,
121 u32 expireval, struct para_data_s *para);
125 static void
126 write_uid( KBNODE root, const char *s )
128 PACKET *pkt = xcalloc (1,sizeof *pkt );
129 size_t n = strlen(s);
131 pkt->pkttype = PKT_USER_ID;
132 pkt->pkt.user_id = xcalloc (1, sizeof *pkt->pkt.user_id + n - 1 );
133 pkt->pkt.user_id->len = n;
134 pkt->pkt.user_id->ref = 1;
135 strcpy(pkt->pkt.user_id->name, s);
136 add_kbnode( root, new_kbnode( pkt ) );
139 static void
140 do_add_key_flags (PKT_signature *sig, unsigned int use)
142 byte buf[1];
144 if (!use)
145 return;
147 buf[0] = 0;
148 if (use & PUBKEY_USAGE_SIG)
150 if(sig->sig_class==0x18)
151 buf[0] |= 0x02; /* Don't set the certify flag for subkeys */
152 else
153 buf[0] |= 0x01 | 0x02;
155 if (use & PUBKEY_USAGE_ENC)
156 buf[0] |= 0x04 | 0x08;
157 if (use & PUBKEY_USAGE_AUTH)
158 buf[0] |= 0x20;
159 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
164 keygen_add_key_expire( PKT_signature *sig, void *opaque )
166 PKT_public_key *pk = opaque;
167 byte buf[8];
168 u32 u;
170 if( pk->expiredate ) {
171 if(pk->expiredate > pk->timestamp)
172 u= pk->expiredate - pk->timestamp;
173 else
174 u= 0;
176 buf[0] = (u >> 24) & 0xff;
177 buf[1] = (u >> 16) & 0xff;
178 buf[2] = (u >> 8) & 0xff;
179 buf[3] = u & 0xff;
180 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
182 else
184 /* Make sure we don't leave a key expiration subpacket lying
185 around */
186 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
189 return 0;
192 static int
193 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
195 struct opaque_data_usage_and_pk *oduap = opaque;
197 do_add_key_flags (sig, oduap->usage);
198 return keygen_add_key_expire (sig, oduap->pk);
201 static int
202 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
204 int i;
206 for (i=0; i < *nbuf; i++ )
207 if (buf[i] == val)
209 log_info (_("preference `%s' duplicated\n"), item);
210 return -1;
213 if (*nbuf >= MAX_PREFS)
215 if(type==1)
216 log_info(_("too many cipher preferences\n"));
217 else if(type==2)
218 log_info(_("too many digest preferences\n"));
219 else if(type==3)
220 log_info(_("too many compression preferences\n"));
221 else
222 BUG();
224 return -1;
227 buf[(*nbuf)++] = val;
228 return 0;
231 #ifdef USE_AES
232 #define AES "S9 S8 S7 "
233 #else
234 #define AES ""
235 #endif
237 #ifdef USE_CAST5
238 #define CAST5 "S3 "
239 #else
240 #define CAST5 ""
241 #endif
244 * Parse the supplied string and use it to set the standard
245 * preferences. The string may be in a form like the one printed by
246 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
247 * cipher/hash/compress names. Use NULL to set the default
248 * preferences. Returns: 0 = okay
251 keygen_set_std_prefs (const char *string,int personal)
253 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
254 int nsym=0, nhash=0, nzip=0, val, rc=0;
255 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
257 if (!string || !ascii_strcasecmp (string, "default")) {
258 if (opt.def_preference_list)
259 string=opt.def_preference_list;
260 else if ( !openpgp_cipher_test_algo(CIPHER_ALGO_IDEA) )
261 string = AES CAST5 "S2 S1 H2 H3 Z2 Z1";
262 else
263 string = AES CAST5 "S2 H2 H3 Z2 Z1";
265 /* If we have it, IDEA goes *after* 3DES so it won't be used
266 unless we're encrypting along with a V3 key. Ideally, we
267 would only put the S1 preference in if the key was RSA and
268 <=2048 bits, as that is what won't break PGP2, but that is
269 difficult with the current code, and not really worth
270 checking as a non-RSA <=2048 bit key wouldn't be usable by
271 PGP2 anyway. -dms */
273 else if (!ascii_strcasecmp (string, "none"))
274 string = "";
276 if(strlen(string))
278 char *tok,*prefstring;
280 prefstring=xstrdup (string); /* need a writable string! */
282 while((tok=strsep(&prefstring," ,")))
284 if((val=openpgp_cipher_map_name(tok)))
286 if(set_one_pref(val,1,tok,sym,&nsym))
287 rc=-1;
289 else if((val=openpgp_md_map_name(tok)))
291 if(set_one_pref(val,2,tok,hash,&nhash))
292 rc=-1;
294 else if((val=string_to_compress_algo(tok))>-1)
296 if(set_one_pref(val,3,tok,zip,&nzip))
297 rc=-1;
299 else if (ascii_strcasecmp(tok,"mdc")==0)
300 mdc=1;
301 else if (ascii_strcasecmp(tok,"no-mdc")==0)
302 mdc=0;
303 else if (ascii_strcasecmp(tok,"ks-modify")==0)
304 modify=1;
305 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
306 modify=0;
307 else
309 log_info (_("invalid item `%s' in preference string\n"),tok);
311 /* Complain if IDEA is not available. */
312 if(ascii_strcasecmp(tok,"s1")==0
313 || ascii_strcasecmp(tok,"idea")==0)
314 idea_cipher_warn(1);
316 rc=-1;
320 xfree (prefstring);
323 if(!rc)
325 if(personal)
327 if(personal==PREFTYPE_SYM)
329 xfree (opt.personal_cipher_prefs);
331 if(nsym==0)
332 opt.personal_cipher_prefs=NULL;
333 else
335 int i;
337 opt.personal_cipher_prefs=
338 xmalloc (sizeof(prefitem_t *)*(nsym+1));
340 for (i=0; i<nsym; i++)
342 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
343 opt.personal_cipher_prefs[i].value = sym[i];
346 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
347 opt.personal_cipher_prefs[i].value = 0;
350 else if(personal==PREFTYPE_HASH)
352 xfree (opt.personal_digest_prefs);
354 if(nhash==0)
355 opt.personal_digest_prefs=NULL;
356 else
358 int i;
360 opt.personal_digest_prefs=
361 xmalloc (sizeof(prefitem_t *)*(nhash+1));
363 for (i=0; i<nhash; i++)
365 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
366 opt.personal_digest_prefs[i].value = hash[i];
369 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
370 opt.personal_digest_prefs[i].value = 0;
373 else if(personal==PREFTYPE_ZIP)
375 xfree (opt.personal_compress_prefs);
377 if(nzip==0)
378 opt.personal_compress_prefs=NULL;
379 else
381 int i;
383 opt.personal_compress_prefs=
384 xmalloc (sizeof(prefitem_t *)*(nzip+1));
386 for (i=0; i<nzip; i++)
388 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
389 opt.personal_compress_prefs[i].value = zip[i];
392 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
393 opt.personal_compress_prefs[i].value = 0;
397 else
399 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
400 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
401 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
402 mdc_available = mdc;
403 ks_modify = modify;
404 prefs_initialized = 1;
408 return rc;
411 #undef CAST5
412 #undef AES
414 /* Return a fake user ID containing the preferences. Caller must
415 free. */
416 PKT_user_id *keygen_get_std_prefs(void)
418 int i,j=0;
419 PKT_user_id *uid=xcalloc (1,sizeof(PKT_user_id));
421 if(!prefs_initialized)
422 keygen_set_std_prefs(NULL,0);
424 uid->prefs=xmalloc ((sizeof(prefitem_t *)*
425 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
427 for(i=0;i<nsym_prefs;i++,j++)
429 uid->prefs[j].type=PREFTYPE_SYM;
430 uid->prefs[j].value=sym_prefs[i];
433 for(i=0;i<nhash_prefs;i++,j++)
435 uid->prefs[j].type=PREFTYPE_HASH;
436 uid->prefs[j].value=hash_prefs[i];
439 for(i=0;i<nzip_prefs;i++,j++)
441 uid->prefs[j].type=PREFTYPE_ZIP;
442 uid->prefs[j].value=zip_prefs[i];
445 uid->prefs[j].type=PREFTYPE_NONE;
446 uid->prefs[j].value=0;
448 uid->mdc_feature=mdc_available;
449 uid->ks_modify=ks_modify;
451 return uid;
454 static void
455 add_feature_mdc (PKT_signature *sig,int enabled)
457 const byte *s;
458 size_t n;
459 int i;
460 char *buf;
462 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
463 /* Already set or cleared */
464 if (s && n &&
465 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
466 return;
468 if (!s || !n) { /* create a new one */
469 n = 1;
470 buf = xcalloc (1,n);
472 else {
473 buf = xmalloc (n);
474 memcpy (buf, s, n);
477 if(enabled)
478 buf[0] |= 0x01; /* MDC feature */
479 else
480 buf[0] &= ~0x01;
482 /* Are there any bits set? */
483 for(i=0;i<n;i++)
484 if(buf[i]!=0)
485 break;
487 if(i==n)
488 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
489 else
490 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
492 xfree (buf);
495 static void
496 add_keyserver_modify (PKT_signature *sig,int enabled)
498 const byte *s;
499 size_t n;
500 int i;
501 char *buf;
503 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
504 enabled=!enabled;
506 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
507 /* Already set or cleared */
508 if (s && n &&
509 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
510 return;
512 if (!s || !n) { /* create a new one */
513 n = 1;
514 buf = xcalloc (1,n);
516 else {
517 buf = xmalloc (n);
518 memcpy (buf, s, n);
521 if(enabled)
522 buf[0] |= 0x80; /* no-modify flag */
523 else
524 buf[0] &= ~0x80;
526 /* Are there any bits set? */
527 for(i=0;i<n;i++)
528 if(buf[i]!=0)
529 break;
531 if(i==n)
532 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
533 else
534 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
536 xfree (buf);
540 keygen_upd_std_prefs( PKT_signature *sig, void *opaque )
542 if (!prefs_initialized)
543 keygen_set_std_prefs (NULL, 0);
545 if (nsym_prefs)
546 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
547 else
549 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
550 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
553 if (nhash_prefs)
554 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
555 else
557 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
558 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
561 if (nzip_prefs)
562 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
563 else
565 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
566 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
569 /* Make sure that the MDC feature flag is set if needed */
570 add_feature_mdc (sig,mdc_available);
571 add_keyserver_modify (sig,ks_modify);
573 return 0;
577 /****************
578 * Add preference to the self signature packet.
579 * This is only called for packets with version > 3.
583 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
585 PKT_public_key *pk = opaque;
587 do_add_key_flags (sig, pk->pubkey_usage);
588 keygen_add_key_expire( sig, opaque );
589 keygen_upd_std_prefs (sig, opaque);
591 return 0;
596 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
598 const char *url=opaque;
600 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
602 return 0;
607 keygen_add_revkey(PKT_signature *sig, void *opaque)
609 struct revocation_key *revkey=opaque;
610 byte buf[2+MAX_FINGERPRINT_LEN];
612 buf[0]=revkey->class;
613 buf[1]=revkey->algid;
614 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
616 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
618 /* All sigs with revocation keys set are nonrevocable */
619 sig->flags.revocable=0;
620 buf[0] = 0;
621 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
623 parse_revkeys(sig);
625 return 0;
628 static int
629 write_direct_sig( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
630 struct revocation_key *revkey )
632 PACKET *pkt;
633 PKT_signature *sig;
634 int rc=0;
635 KBNODE node;
636 PKT_public_key *pk;
638 if( opt.verbose )
639 log_info(_("writing direct signature\n"));
641 /* get the pk packet from the pub_tree */
642 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
643 if( !node )
644 BUG();
645 pk = node->pkt->pkt.public_key;
647 /* we have to cache the key, so that the verification of the signature
648 * creation is able to retrieve the public key */
649 cache_public_key (pk);
651 /* and make the signature */
652 rc = make_keysig_packet(&sig,pk,NULL,NULL,sk,0x1F,0,0,0,0,
653 keygen_add_revkey,revkey);
654 if( rc ) {
655 log_error("make_keysig_packet failed: %s\n", gpg_strerror (rc) );
656 return rc;
659 pkt = xcalloc (1, sizeof *pkt );
660 pkt->pkttype = PKT_SIGNATURE;
661 pkt->pkt.signature = sig;
662 add_kbnode( root, new_kbnode( pkt ) );
663 return rc;
666 static int
667 write_selfsig( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
668 unsigned int use )
670 PACKET *pkt;
671 PKT_signature *sig;
672 PKT_user_id *uid;
673 int rc=0;
674 KBNODE node;
675 PKT_public_key *pk;
677 if( opt.verbose )
678 log_info(_("writing self signature\n"));
680 /* get the uid packet from the list */
681 node = find_kbnode( root, PKT_USER_ID );
682 if( !node )
683 BUG(); /* no user id packet in tree */
684 uid = node->pkt->pkt.user_id;
685 /* get the pk packet from the pub_tree */
686 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
687 if( !node )
688 BUG();
689 pk = node->pkt->pkt.public_key;
690 pk->pubkey_usage = use;
691 /* we have to cache the key, so that the verification of the signature
692 * creation is able to retrieve the public key */
693 cache_public_key (pk);
695 /* and make the signature */
696 rc = make_keysig_packet( &sig, pk, uid, NULL, sk, 0x13, 0, 0, 0, 0,
697 keygen_add_std_prefs, pk );
698 if( rc ) {
699 log_error("make_keysig_packet failed: %s\n", gpg_strerror (rc) );
700 return rc;
703 pkt = xcalloc (1, sizeof *pkt );
704 pkt->pkttype = PKT_SIGNATURE;
705 pkt->pkt.signature = sig;
706 add_kbnode( root, new_kbnode( pkt ) );
707 return rc;
710 static int
711 write_keybinding( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
712 unsigned int use )
714 PACKET *pkt;
715 PKT_signature *sig;
716 int rc=0;
717 KBNODE node;
718 PKT_public_key *pk, *subpk;
719 struct opaque_data_usage_and_pk oduap;
721 if( opt.verbose )
722 log_info(_("writing key binding signature\n"));
724 /* get the pk packet from the pub_tree */
725 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
726 if( !node )
727 BUG();
728 pk = node->pkt->pkt.public_key;
729 /* we have to cache the key, so that the verification of the signature
730 * creation is able to retrieve the public key */
731 cache_public_key (pk);
733 /* find the last subkey */
734 subpk = NULL;
735 for(node=pub_root; node; node = node->next ) {
736 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
737 subpk = node->pkt->pkt.public_key;
739 if( !subpk )
740 BUG();
742 /* and make the signature */
743 oduap.usage = use;
744 oduap.pk = subpk;
745 rc = make_keysig_packet( &sig, pk, NULL, subpk, sk, 0x18, 0, 0, 0, 0,
746 keygen_add_key_flags_and_expire, &oduap );
747 if( rc ) {
748 log_error("make_keysig_packet failed: %s\n", gpg_strerror (rc) );
749 return rc;
752 pkt = xcalloc (1, sizeof *pkt );
753 pkt->pkttype = PKT_SIGNATURE;
754 pkt->pkt.signature = sig;
755 add_kbnode( root, new_kbnode( pkt ) );
756 return rc;
760 static int
761 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
762 const char *topname, const char *elems)
764 gcry_sexp_t list, l2;
765 const char *s;
766 int i, idx;
767 int rc = 0;
769 list = gcry_sexp_find_token (sexp, topname, 0);
770 if (!list)
771 return gpg_error (GPG_ERR_INV_OBJ);
772 l2 = gcry_sexp_cadr (list);
773 gcry_sexp_release (list);
774 list = l2;
775 if (!list)
776 return gpg_error (GPG_ERR_NO_OBJ);
778 for (idx=0,s=elems; *s; s++, idx++)
780 l2 = gcry_sexp_find_token (list, s, 1);
781 if (!l2)
783 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
784 goto leave;
786 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
787 gcry_sexp_release (l2);
788 if (!array[idx])
790 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
791 goto leave;
794 gcry_sexp_release (list);
796 leave:
797 if (rc)
799 for (i=0; i<idx; i++)
801 xfree (array[i]);
802 array[i] = NULL;
804 gcry_sexp_release (list);
806 return rc;
810 static int
811 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
813 int rc = 0;
815 if (dek)
817 sk->protect.algo = dek->algo;
818 sk->protect.s2k = *s2k;
819 rc = protect_secret_key (sk, dek);
820 if (rc)
821 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
824 return rc;
827 static void
828 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
830 size_t n;
831 char *buf;
833 if (misc_key_info)
835 /* DSA: don't know whether it makes sense to have the factors, so for now
836 we store them in the secret keyring (but they are not secret)
837 p = 2 * q * f1 * f2 * ... * fn
838 We store only f1 to f_n-1; fn can be calculated because p and q
839 are known. */
840 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
841 buf = xmalloc (n+4);
842 strcpy (buf, "#::");
843 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
844 if (n)
846 n += 3;
847 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
849 xfree (buf);
850 gcry_sexp_release (misc_key_info);
855 static int
856 gen_elg(int algo, unsigned int nbits,
857 KBNODE pub_root, KBNODE sec_root, DEK *dek,
858 STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
860 int rc;
861 PACKET *pkt;
862 PKT_secret_key *sk;
863 PKT_public_key *pk;
864 gcry_sexp_t s_parms, s_key;
865 gcry_sexp_t misc_key_info;
867 assert (is_ELGAMAL(algo));
869 if (nbits < 512)
871 nbits = 1024;
872 log_info (_("keysize invalid; using %u bits\n"), nbits);
875 if ((nbits % 32))
877 nbits = ((nbits + 31) / 32) * 32;
878 log_info (_("keysize rounded up to %u bits\n"), nbits);
881 rc = gcry_sexp_build ( &s_parms, NULL,
882 "(genkey(%s(nbits %d)))",
883 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
884 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
885 (int)nbits);
886 if (rc)
887 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
889 rc = gcry_pk_genkey (&s_key, s_parms);
890 gcry_sexp_release (s_parms);
891 if (rc)
893 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
894 return rc;
897 sk = xcalloc (1, sizeof *sk);
898 pk = xcalloc (1, sizeof *pk);
899 sk->timestamp = pk->timestamp = make_timestamp();
900 sk->version = pk->version = 4;
901 if (expireval)
902 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
903 sk->pubkey_algo = pk->pubkey_algo = algo;
905 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
906 if (rc)
908 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
909 gcry_sexp_release (s_key);
910 return rc;
912 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
913 if (rc)
915 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
916 gcry_sexp_release (s_key);
917 return rc;
919 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
920 gcry_sexp_release (s_key);
922 sk->is_protected = 0;
923 sk->protect.algo = 0;
925 sk->csum = checksum_mpi (sk->skey[3]);
926 if (ret_sk) /* not a subkey: return an unprotected version of the sk */
927 *ret_sk = copy_secret_key (NULL, sk);
929 rc = genhelp_protect (dek, s2k, sk);
930 if (rc)
932 free_public_key (pk);
933 free_secret_key (sk);
934 gcry_sexp_release (misc_key_info);
935 return rc;
938 pkt = xcalloc (1,sizeof *pkt);
939 pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
940 pkt->pkt.public_key = pk;
941 add_kbnode(pub_root, new_kbnode( pkt ));
943 /* don't know whether it makes sense to have the factors, so for now
944 * we store them in the secret keyring (but they are not secret) */
945 pkt = xcalloc (1,sizeof *pkt);
946 pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
947 pkt->pkt.secret_key = sk;
948 add_kbnode(sec_root, new_kbnode( pkt ));
950 genhelp_factors (misc_key_info, sec_root);
952 return 0;
956 /****************
957 * Generate a DSA key
959 static int
960 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
961 STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
963 int rc;
964 PACKET *pkt;
965 PKT_secret_key *sk;
966 PKT_public_key *pk;
967 gcry_sexp_t s_parms, s_key;
968 gcry_sexp_t misc_key_info;
970 if (nbits > 1024 || nbits < 512)
972 nbits = 1024;
973 log_info(_("keysize invalid; using %u bits\n"), nbits);
976 if ((nbits % 64))
978 nbits = ((nbits + 63) / 64) * 64;
979 log_info (_("keysize rounded up to %u bits\n"), nbits);
982 rc = gcry_sexp_build (&s_parms, NULL,
983 "(genkey(dsa(nbits %d)))",
984 (int)nbits);
985 if (rc)
986 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
988 rc = gcry_pk_genkey (&s_key, s_parms);
989 gcry_sexp_release (s_parms);
990 if (rc)
992 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
993 return rc;
996 sk = xcalloc (1, sizeof *sk );
997 pk = xcalloc (1, sizeof *pk );
998 sk->timestamp = pk->timestamp = make_timestamp();
999 sk->version = pk->version = 4;
1000 if (expireval)
1001 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1002 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1004 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1005 if (rc)
1007 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1008 gcry_sexp_release (s_key);
1009 return rc;
1011 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1012 if (rc)
1014 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1015 gcry_sexp_release (s_key);
1016 return rc;
1018 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1019 gcry_sexp_release (s_key);
1021 sk->is_protected = 0;
1022 sk->protect.algo = 0;
1024 sk->csum = checksum_mpi ( sk->skey[4] );
1025 if (ret_sk) /* not a subkey: return an unprotected version of the sk */
1026 *ret_sk = copy_secret_key( NULL, sk );
1028 rc = genhelp_protect (dek, s2k, sk);
1029 if (rc)
1031 free_public_key (pk);
1032 free_secret_key (sk);
1033 gcry_sexp_release (misc_key_info);
1034 return rc;
1037 pkt = xcalloc (1,sizeof *pkt);
1038 pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
1039 pkt->pkt.public_key = pk;
1040 add_kbnode(pub_root, new_kbnode( pkt ));
1042 pkt = xcalloc (1,sizeof *pkt);
1043 pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
1044 pkt->pkt.secret_key = sk;
1045 add_kbnode(sec_root, new_kbnode( pkt ));
1047 genhelp_factors (misc_key_info, sec_root);
1049 return 0;
1054 * Generate an RSA key.
1056 static int
1057 gen_rsa(int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1058 STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
1060 int rc;
1061 PACKET *pkt;
1062 PKT_secret_key *sk;
1063 PKT_public_key *pk;
1064 gcry_sexp_t s_parms, s_key;
1066 assert (is_RSA(algo));
1068 if (nbits < 1024)
1070 nbits = 1024;
1071 log_info(_("keysize invalid; using %u bits\n"), nbits);
1074 if ((nbits % 32))
1076 nbits = ((nbits + 31) / 32) * 32;
1077 log_info (_("keysize rounded up to %u bits\n"), nbits);
1080 rc = gcry_sexp_build (&s_parms, NULL,
1081 "(genkey(rsa(nbits %d)))",
1082 (int)nbits);
1083 if (rc)
1084 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1086 rc = gcry_pk_genkey (&s_key, s_parms);
1087 gcry_sexp_release (s_parms);
1088 if (rc)
1090 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1091 return rc;
1094 sk = xcalloc (1, sizeof *sk );
1095 pk = xcalloc (1, sizeof *pk );
1096 sk->timestamp = pk->timestamp = make_timestamp();
1097 sk->version = pk->version = 4;
1098 if (expireval)
1099 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1100 sk->pubkey_algo = pk->pubkey_algo = algo;
1102 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1103 if (rc)
1105 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1106 gcry_sexp_release (s_key);
1107 return rc;
1109 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1110 if (rc)
1112 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1113 gcry_sexp_release (s_key);
1114 return rc;
1116 gcry_sexp_release (s_key);
1118 sk->is_protected = 0;
1119 sk->protect.algo = 0;
1121 sk->csum = checksum_mpi (sk->skey[2] );
1122 sk->csum += checksum_mpi (sk->skey[3] );
1123 sk->csum += checksum_mpi (sk->skey[4] );
1124 sk->csum += checksum_mpi (sk->skey[5] );
1125 if (ret_sk) /* not a subkey: return an unprotected version of the sk */
1126 *ret_sk = copy_secret_key (NULL, sk);
1128 rc = genhelp_protect (dek, s2k, sk);
1129 if (rc)
1131 free_public_key (pk);
1132 free_secret_key (sk);
1133 return rc;
1136 pkt = xcalloc (1,sizeof *pkt);
1137 pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
1138 pkt->pkt.public_key = pk;
1139 add_kbnode (pub_root, new_kbnode( pkt ));
1141 pkt = xcalloc (1,sizeof *pkt);
1142 pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
1143 pkt->pkt.secret_key = sk;
1144 add_kbnode(sec_root, new_kbnode( pkt ));
1146 return 0;
1150 /****************
1151 * check valid days:
1152 * return 0 on error or the multiplier
1154 static int
1155 check_valid_days( const char *s )
1157 if( !digitp(s) )
1158 return 0;
1159 for( s++; *s; s++)
1160 if( !digitp(s) )
1161 break;
1162 if( !*s )
1163 return 1;
1164 if( s[1] )
1165 return 0; /* e.g. "2323wc" */
1166 if( *s == 'd' || *s == 'D' )
1167 return 1;
1168 if( *s == 'w' || *s == 'W' )
1169 return 7;
1170 if( *s == 'm' || *s == 'M' )
1171 return 30;
1172 if( *s == 'y' || *s == 'Y' )
1173 return 365;
1174 return 0;
1178 /****************
1179 * Returns: 0 to create both a DSA and a ElGamal key.
1180 * and only if key flags are to be written the desired usage.
1182 static int
1183 ask_algo (int addmode, unsigned int *r_usage)
1185 char *answer;
1186 int algo;
1188 *r_usage = 0;
1189 tty_printf(_("Please select what kind of key you want:\n"));
1190 if( !addmode )
1191 tty_printf(_(" (%d) DSA and ElGamal (default)\n"), 1 );
1192 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
1193 if( addmode )
1194 tty_printf( _(" (%d) ElGamal (encrypt only)\n"), 3 );
1195 if (opt.expert)
1196 tty_printf( _(" (%d) ElGamal (sign and encrypt)\n"), 4 );
1197 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
1198 if (addmode)
1199 tty_printf( _(" (%d) RSA (encrypt only)\n"), 6 );
1200 if (opt.expert)
1201 tty_printf( _(" (%d) RSA (sign and encrypt)\n"), 7 );
1203 for(;;) {
1204 answer = cpr_get("keygen.algo",_("Your selection? "));
1205 cpr_kill_prompt();
1206 algo = *answer? atoi(answer): 1;
1207 xfree (answer);
1208 if( algo == 1 && !addmode ) {
1209 algo = 0; /* create both keys */
1210 break;
1212 else if( algo == 7 && opt.expert ) {
1213 algo = PUBKEY_ALGO_RSA;
1214 *r_usage = PUBKEY_USAGE_ENC | PUBKEY_USAGE_SIG;
1215 break;
1217 else if( algo == 6 && addmode ) {
1218 algo = PUBKEY_ALGO_RSA;
1219 *r_usage = PUBKEY_USAGE_ENC;
1220 break;
1222 else if( algo == 5 ) {
1223 algo = PUBKEY_ALGO_RSA;
1224 *r_usage = PUBKEY_USAGE_SIG;
1225 break;
1227 else if( algo == 4 && opt.expert)
1229 tty_printf(_(
1230 "The use of this algorithm is only supported by GnuPG. You will not be\n"
1231 "able to use this key to communicate with PGP users. This algorithm is also\n"
1232 "very slow, and may not be as secure as the other choices.\n"));
1234 if( cpr_get_answer_is_yes("keygen.algo.elg_se",
1235 _("Create anyway? ")))
1237 algo = PUBKEY_ALGO_ELGAMAL;
1238 *r_usage = PUBKEY_USAGE_ENC | PUBKEY_USAGE_SIG;
1239 break;
1242 else if( algo == 3 && addmode ) {
1243 algo = PUBKEY_ALGO_ELGAMAL_E;
1244 *r_usage = PUBKEY_USAGE_ENC;
1245 break;
1247 else if( algo == 2 ) {
1248 algo = PUBKEY_ALGO_DSA;
1249 *r_usage = PUBKEY_USAGE_SIG;
1250 break;
1252 else
1253 tty_printf(_("Invalid selection.\n"));
1255 return algo;
1259 static unsigned
1260 ask_keysize( int algo )
1262 char *answer;
1263 unsigned nbits;
1265 if (algo != PUBKEY_ALGO_DSA && algo != PUBKEY_ALGO_RSA) {
1266 tty_printf (_("About to generate a new %s keypair.\n"
1267 " minimum keysize is 768 bits\n"
1268 " default keysize is 1024 bits\n"
1269 " highest suggested keysize is 2048 bits\n"),
1270 gcry_pk_algo_name (algo) );
1273 for(;;) {
1274 answer = cpr_get("keygen.size",
1275 _("What keysize do you want? (1024) "));
1276 cpr_kill_prompt();
1277 nbits = *answer? atoi(answer): 1024;
1278 xfree (answer);
1279 if( algo == PUBKEY_ALGO_DSA && (nbits < 512 || nbits > 1024) )
1280 tty_printf(_("DSA only allows keysizes from 512 to 1024\n"));
1281 else if( algo == PUBKEY_ALGO_RSA && nbits < 1024 )
1282 tty_printf(_("keysize too small;"
1283 " 1024 is smallest value allowed for RSA.\n"));
1284 else if( nbits < 768 )
1285 tty_printf(_("keysize too small;"
1286 " 768 is smallest value allowed.\n"));
1287 else if( nbits > 4096 ) {
1288 /* It is ridiculous and an annoyance to use larger key sizes!
1289 * GnuPG can handle much larger sizes; but it takes an eternity
1290 * to create such a key (but less than the time the Sirius
1291 * Computer Corporation needs to process one of the usual
1292 * complaints) and {de,en}cryption although needs some time.
1293 * So, before you complain about this limitation, I suggest that
1294 * you start a discussion with Marvin about this theme and then
1295 * do whatever you want. */
1296 tty_printf(_("keysize too large; %d is largest value allowed.\n"),
1297 4096);
1299 else if( nbits > 2048 && !cpr_enabled() ) {
1300 tty_printf(
1301 _("Keysizes larger than 2048 are not suggested because\n"
1302 "computations take REALLY long!\n"));
1303 if( cpr_get_answer_is_yes("keygen.size.huge.okay",_(
1304 "Are you sure that you want this keysize? ")) ) {
1305 tty_printf(_("Okay, but keep in mind that your monitor "
1306 "and keyboard radiation is also very vulnerable "
1307 "to attacks!\n"));
1308 break;
1311 else
1312 break;
1314 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1315 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) ) {
1316 nbits = ((nbits + 63) / 64) * 64;
1317 tty_printf(_("rounded up to %u bits\n"), nbits );
1319 else if( (nbits % 32) ) {
1320 nbits = ((nbits + 31) / 32) * 32;
1321 tty_printf(_("rounded up to %u bits\n"), nbits );
1323 return nbits;
1327 /****************
1328 * Parse an expire string and return it's value in days.
1329 * Returns -1 on error.
1331 static int
1332 parse_expire_string( const char *string )
1334 int mult;
1335 u32 abs_date=0;
1336 u32 curtime = make_timestamp();
1337 int valid_days;
1339 if( !*string )
1340 valid_days = 0;
1341 else if( (abs_date = scan_isodatestr(string)) && abs_date > curtime ) {
1342 /* This calculation is not perfectly okay because we
1343 * are later going to simply multiply by 86400 and don't
1344 * correct for leapseconds. A solution would be to change
1345 * the whole implemenation to work with dates and not intervals
1346 * which are required for v3 keys.
1348 valid_days = abs_date/86400-curtime/86400+1;
1350 else if( (mult=check_valid_days(string)) ) {
1351 valid_days = atoi(string) * mult;
1352 if( valid_days < 0 || valid_days > 39447 )
1353 valid_days = 0;
1355 else {
1356 valid_days = -1;
1358 return valid_days;
1361 /* object == 0 for a key, and 1 for a sig */
1363 ask_expire_interval(int object)
1365 char *answer;
1366 int valid_days=0;
1367 u32 interval = 0;
1369 switch(object)
1371 case 0:
1372 tty_printf(_("Please specify how long the key should be valid.\n"
1373 " 0 = key does not expire\n"
1374 " <n> = key expires in n days\n"
1375 " <n>w = key expires in n weeks\n"
1376 " <n>m = key expires in n months\n"
1377 " <n>y = key expires in n years\n"));
1378 break;
1380 case 1:
1381 tty_printf(_("Please specify how long the signature should be valid.\n"
1382 " 0 = signature does not expire\n"
1383 " <n> = signature expires in n days\n"
1384 " <n>w = signature expires in n weeks\n"
1385 " <n>m = signature expires in n months\n"
1386 " <n>y = signature expires in n years\n"));
1387 break;
1389 default:
1390 BUG();
1393 /* Note: The elgamal subkey for DSA has no expiration date because
1394 * it must be signed with the DSA key and this one has the expiration
1395 * date */
1397 answer = NULL;
1398 for(;;) {
1399 u32 curtime=make_timestamp();
1401 xfree (answer);
1402 if(object==0)
1403 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1404 else
1405 answer = cpr_get("siggen.valid",_("Signature is valid for? (0) "));
1406 cpr_kill_prompt();
1407 trim_spaces(answer);
1408 valid_days = parse_expire_string( answer );
1409 if( valid_days < 0 ) {
1410 tty_printf(_("invalid value\n"));
1411 continue;
1414 if( !valid_days ) {
1415 tty_printf(_("%s does not expire at all\n"),
1416 object==0?"Key":"Signature");
1417 interval = 0;
1419 else {
1420 interval = valid_days * 86400L;
1421 /* print the date when the key expires */
1422 tty_printf(_("%s expires at %s\n"),
1423 object==0?"Key":"Signature",
1424 asctimestamp((ulong)(curtime + interval) ) );
1425 /* FIXME: This check yields warning some machines: write a
1426 configure check and do this check here only for 32 bit
1427 machines */
1428 if( (time_t)((ulong)(curtime+interval)) < 0 )
1429 tty_printf(_("Your system can't display dates beyond 2038.\n"
1430 "However, it will be correctly handled up to 2106.\n"));
1433 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1434 _("Is this correct (y/n)? ")) )
1435 break;
1437 xfree (answer);
1438 return interval;
1442 ask_expiredate()
1444 u32 x = ask_expire_interval(0);
1445 return x? make_timestamp() + x : 0;
1449 static int
1450 count_chr( const char *string, int c )
1452 int count;
1454 for (count=0; *string; string++ )
1455 if ( *string == c )
1456 count++;
1457 return count;
1461 static int
1462 has_invalid_email_chars( const char *s )
1464 int at_seen=0;
1465 static char valid_chars[] = "01234567890_-."
1466 "abcdefghijklmnopqrstuvwxyz"
1467 "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1469 for( ; *s; s++ ) {
1470 if( *s & 0x80 )
1471 return 1;
1472 if( *s == '@' )
1473 at_seen=1;
1474 else if( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1475 return 1;
1476 else if( at_seen && !strchr( valid_chars, *s ) )
1477 return 1;
1479 return 0;
1483 static char *
1484 ask_user_id( int mode )
1486 char *answer;
1487 char *aname, *acomment, *amail, *uid;
1489 if( !mode )
1490 tty_printf( _("\n"
1491 "You need a User-ID to identify your key; the software constructs the user id\n"
1492 "from Real Name, Comment and Email Address in this form:\n"
1493 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n") );
1494 uid = aname = acomment = amail = NULL;
1495 for(;;) {
1496 char *p;
1497 int fail=0;
1499 if( !aname ) {
1500 for(;;) {
1501 xfree (aname);
1502 aname = cpr_get("keygen.name",_("Real name: "));
1503 trim_spaces(aname);
1504 cpr_kill_prompt();
1506 if( opt.allow_freeform_uid )
1507 break;
1509 if( strpbrk( aname, "<>" ) )
1510 tty_printf(_("Invalid character in name\n"));
1511 else if( digitp(aname) )
1512 tty_printf(_("Name may not start with a digit\n"));
1513 else if( strlen(aname) < 5 )
1514 tty_printf(_("Name must be at least 5 characters long\n"));
1515 else
1516 break;
1519 if( !amail ) {
1520 for(;;) {
1521 xfree (amail);
1522 amail = cpr_get("keygen.email",_("Email address: "));
1523 trim_spaces(amail);
1524 cpr_kill_prompt();
1525 if( !*amail || opt.allow_freeform_uid )
1526 break; /* no email address is okay */
1527 else if( has_invalid_email_chars(amail)
1528 || count_chr(amail,'@') != 1
1529 || *amail == '@'
1530 || amail[strlen(amail)-1] == '@'
1531 || amail[strlen(amail)-1] == '.'
1532 || strstr(amail, "..") )
1533 tty_printf(_("Not a valid email address\n"));
1534 else
1535 break;
1538 if( !acomment ) {
1539 for(;;) {
1540 xfree (acomment);
1541 acomment = cpr_get("keygen.comment",_("Comment: "));
1542 trim_spaces(acomment);
1543 cpr_kill_prompt();
1544 if( !*acomment )
1545 break; /* no comment is okay */
1546 else if( strpbrk( acomment, "()" ) )
1547 tty_printf(_("Invalid character in comment\n"));
1548 else
1549 break;
1554 xfree (uid);
1555 uid = p = xmalloc (strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
1556 p = stpcpy(p, aname );
1557 if( *acomment )
1558 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
1559 if( *amail )
1560 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
1562 /* print a note in case that UTF8 mapping has to be done */
1563 for(p=uid; *p; p++ ) {
1564 if( *p & 0x80 ) {
1565 tty_printf(_("You are using the `%s' character set.\n"),
1566 get_native_charset() );
1567 break;
1571 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
1572 /* fixme: add a warning if this user-id already exists */
1573 if( !*amail && !opt.allow_freeform_uid
1574 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
1575 fail = 1;
1576 tty_printf(_("Please don't put the email address "
1577 "into the real name or the comment\n") );
1580 for(;;) {
1581 const char *ansstr = _("NnCcEeOoQq");
1583 if( strlen(ansstr) != 10 )
1584 BUG();
1585 if( cpr_enabled() ) {
1586 answer = xstrdup (ansstr+6);
1587 answer[1] = 0;
1589 else {
1590 answer = cpr_get("keygen.userid.cmd", fail?
1591 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
1592 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
1593 cpr_kill_prompt();
1595 if( strlen(answer) > 1 )
1597 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
1598 xfree (aname); aname = NULL;
1599 break;
1601 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
1602 xfree (acomment); acomment = NULL;
1603 break;
1605 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
1606 xfree (amail); amail = NULL;
1607 break;
1609 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
1610 if( fail ) {
1611 tty_printf(_("Please correct the error first\n"));
1613 else {
1614 xfree (aname); aname = NULL;
1615 xfree (acomment); acomment = NULL;
1616 xfree (amail); amail = NULL;
1617 break;
1620 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
1621 xfree (aname); aname = NULL;
1622 xfree (acomment); acomment = NULL;
1623 xfree (amail); amail = NULL;
1624 xfree (uid); uid = NULL;
1625 break;
1627 xfree (answer);
1629 xfree (answer);
1630 if( !amail && !acomment && !amail )
1631 break;
1632 xfree (uid); uid = NULL;
1634 if( uid ) {
1635 char *p = native_to_utf8( uid );
1636 xfree ( uid );
1637 uid = p;
1639 return uid;
1643 static DEK *
1644 ask_passphrase( STRING2KEY **ret_s2k )
1646 DEK *dek = NULL;
1647 STRING2KEY *s2k;
1648 const char *errtext = NULL;
1650 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
1652 s2k = xmalloc ( sizeof *s2k );
1653 for(;;) {
1654 s2k->mode = opt.s2k_mode;
1655 s2k->hash_algo = opt.s2k_digest_algo;
1656 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k,2,
1657 errtext, NULL);
1658 if( !dek ) {
1659 errtext = N_("passphrase not correctly repeated; try again");
1660 tty_printf(_("%s.\n"), _(errtext));
1662 else if( !dek->keylen ) {
1663 xfree (dek); dek = NULL;
1664 xfree (s2k); s2k = NULL;
1665 tty_printf(_(
1666 "You don't want a passphrase - this is probably a *bad* idea!\n"
1667 "I will do it anyway. You can change your passphrase at any time,\n"
1668 "using this program with the option \"--edit-key\".\n\n"));
1669 break;
1671 else
1672 break; /* okay */
1674 *ret_s2k = s2k;
1675 return dek;
1679 static int
1680 do_create( int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
1681 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk, u32 expiredate )
1683 int rc=0;
1685 if( !opt.batch )
1686 tty_printf(_(
1687 "We need to generate a lot of random bytes. It is a good idea to perform\n"
1688 "some other action (type on the keyboard, move the mouse, utilize the\n"
1689 "disks) during the prime generation; this gives the random number\n"
1690 "generator a better chance to gain enough entropy.\n") );
1692 if( algo == PUBKEY_ALGO_ELGAMAL || algo == PUBKEY_ALGO_ELGAMAL_E )
1693 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1694 else if( algo == PUBKEY_ALGO_DSA )
1695 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1696 else if( algo == PUBKEY_ALGO_RSA )
1697 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1698 else
1699 BUG();
1701 #ifdef ENABLE_COMMENT_PACKETS
1702 if( !rc ) {
1703 add_kbnode( pub_root,
1704 make_comment_node("#created by GNUPG v" VERSION " ("
1705 PRINTABLE_OS_NAME ")"));
1706 add_kbnode( sec_root,
1707 make_comment_node("#created by GNUPG v" VERSION " ("
1708 PRINTABLE_OS_NAME ")"));
1710 #endif
1711 return rc;
1715 /****************
1716 * Generate a new user id packet, or return NULL if canceled
1718 PKT_user_id *
1719 generate_user_id()
1721 PKT_user_id *uid;
1722 char *p;
1723 size_t n;
1725 p = ask_user_id( 1 );
1726 if( !p )
1727 return NULL;
1728 n = strlen(p);
1729 uid = xcalloc (1, sizeof *uid + n - 1 );
1730 uid->len = n;
1731 strcpy(uid->name, p);
1732 uid->ref = 1;
1733 return uid;
1737 static void
1738 release_parameter_list( struct para_data_s *r )
1740 struct para_data_s *r2;
1742 for( ; r ; r = r2 ) {
1743 r2 = r->next;
1744 if( r->key == pPASSPHRASE_DEK )
1745 xfree ( r->u.dek );
1746 else if( r->key == pPASSPHRASE_S2K )
1747 xfree ( r->u.s2k );
1749 xfree (r);
1753 static struct para_data_s *
1754 get_parameter( struct para_data_s *para, enum para_name key )
1756 struct para_data_s *r;
1758 for( r = para; r && r->key != key; r = r->next )
1760 return r;
1763 static const char *
1764 get_parameter_value( struct para_data_s *para, enum para_name key )
1766 struct para_data_s *r = get_parameter( para, key );
1767 return (r && *r->u.value)? r->u.value : NULL;
1770 static int
1771 get_parameter_algo( struct para_data_s *para, enum para_name key )
1773 int i;
1774 struct para_data_s *r = get_parameter( para, key );
1775 if( !r )
1776 return -1;
1777 if( digitp( r->u.value ) )
1778 i = atoi( r->u.value );
1779 else
1780 i = openpgp_pk_map_name ( r->u.value );
1781 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
1782 i = 0; /* we don't want to allow generation of these algorithms */
1783 return i;
1787 * parse the usage parameter and set the keyflags. Return true on error.
1789 static int
1790 parse_parameter_usage (const char *fname,
1791 struct para_data_s *para, enum para_name key)
1793 struct para_data_s *r = get_parameter( para, key );
1794 char *p, *pn;
1795 unsigned int use;
1797 if( !r )
1798 return 0; /* none (this is an optional parameter)*/
1800 use = 0;
1801 pn = r->u.value;
1802 while ( (p = strsep (&pn, " \t,")) ) {
1803 if ( !*p)
1805 else if ( !ascii_strcasecmp (p, "sign") )
1806 use |= PUBKEY_USAGE_SIG;
1807 else if ( !ascii_strcasecmp (p, "encrypt") )
1808 use |= PUBKEY_USAGE_ENC;
1809 else if ( !ascii_strcasecmp (p, "auth") )
1810 use |= PUBKEY_USAGE_AUTH;
1811 else {
1812 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
1813 return -1; /* error */
1816 r->u.usage = use;
1817 return 0;
1820 static int
1821 parse_revocation_key (const char *fname,
1822 struct para_data_s *para, enum para_name key)
1824 struct para_data_s *r = get_parameter( para, key );
1825 struct revocation_key revkey;
1826 char *pn;
1827 int i;
1829 if( !r )
1830 return 0; /* none (this is an optional parameter) */
1832 pn = r->u.value;
1834 revkey.class=0x80;
1835 revkey.algid=atoi(pn);
1836 if(!revkey.algid)
1837 goto fail;
1839 /* Skip to the fpr */
1840 while(*pn && *pn!=':')
1841 pn++;
1843 if(*pn!=':')
1844 goto fail;
1846 pn++;
1848 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
1850 int c=hextobyte(pn);
1851 if(c==-1)
1852 goto fail;
1854 revkey.fpr[i]=c;
1857 /* skip to the tag */
1858 while(*pn && *pn!='s' && *pn!='S')
1859 pn++;
1861 if(ascii_strcasecmp(pn,"sensitive")==0)
1862 revkey.class|=0x40;
1864 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
1866 return 0;
1868 fail:
1869 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
1870 return -1; /* error */
1874 static u32
1875 get_parameter_u32( struct para_data_s *para, enum para_name key )
1877 struct para_data_s *r = get_parameter( para, key );
1879 if( !r )
1880 return 0;
1881 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
1882 return r->u.expire;
1883 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
1884 return r->u.usage;
1886 return (unsigned int)strtoul( r->u.value, NULL, 10 );
1889 static unsigned int
1890 get_parameter_uint( struct para_data_s *para, enum para_name key )
1892 return get_parameter_u32( para, key );
1895 static DEK *
1896 get_parameter_dek( struct para_data_s *para, enum para_name key )
1898 struct para_data_s *r = get_parameter( para, key );
1899 return r? r->u.dek : NULL;
1902 static STRING2KEY *
1903 get_parameter_s2k( struct para_data_s *para, enum para_name key )
1905 struct para_data_s *r = get_parameter( para, key );
1906 return r? r->u.s2k : NULL;
1909 static struct revocation_key *
1910 get_parameter_revkey( struct para_data_s *para, enum para_name key )
1912 struct para_data_s *r = get_parameter( para, key );
1913 return r? &r->u.revkey : NULL;
1916 static int
1917 proc_parameter_file( struct para_data_s *para, const char *fname,
1918 struct output_control_s *outctrl, int card )
1920 struct para_data_s *r;
1921 const char *s1, *s2, *s3;
1922 size_t n;
1923 char *p;
1924 int i;
1926 /* check that we have all required parameters */
1927 assert( get_parameter( para, pKEYTYPE ) );
1928 i = get_parameter_algo( para, pKEYTYPE );
1929 if( i < 1 || openpgp_pk_test_algo ( i, PUBKEY_USAGE_SIG ) ) {
1930 r = get_parameter( para, pKEYTYPE );
1931 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
1932 return -1;
1935 if (parse_parameter_usage (fname, para, pKEYUSAGE))
1936 return -1;
1938 i = get_parameter_algo( para, pSUBKEYTYPE );
1939 if( i > 0 && openpgp_pk_test_algo ( i, 0 ) ) {
1940 r = get_parameter( para, pSUBKEYTYPE );
1941 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
1942 return -1;
1944 if (i > 0 && parse_parameter_usage (fname, para, pSUBKEYUSAGE))
1945 return -1;
1948 if( !get_parameter_value( para, pUSERID ) ) {
1949 /* create the formatted user ID */
1950 s1 = get_parameter_value( para, pNAMEREAL );
1951 s2 = get_parameter_value( para, pNAMECOMMENT );
1952 s3 = get_parameter_value( para, pNAMEEMAIL );
1953 if( s1 || s2 || s3 ) {
1954 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
1955 r = xcalloc (1, sizeof *r + n + 20 );
1956 r->key = pUSERID;
1957 p = r->u.value;
1958 if( s1 )
1959 p = stpcpy(p, s1 );
1960 if( s2 )
1961 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
1962 if( s3 )
1963 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
1964 r->next = para;
1965 para = r;
1969 /* Set preferences, if any. */
1970 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
1972 /* Set revoker, if any. */
1973 if (parse_revocation_key (fname, para, pREVOKER))
1974 return -1;
1976 /* make DEK and S2K from the Passphrase */
1977 r = get_parameter( para, pPASSPHRASE );
1978 if( r && *r->u.value ) {
1979 /* we have a plain text passphrase - create a DEK from it.
1980 * It is a little bit ridiculous to keep it in secure memory
1981 * but because we do this always, why not here. */
1982 STRING2KEY *s2k;
1983 DEK *dek;
1985 s2k = xmalloc_secure ( sizeof *s2k );
1986 s2k->mode = opt.s2k_mode;
1987 s2k->hash_algo = opt.s2k_digest_algo;
1988 set_next_passphrase( r->u.value );
1989 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2,
1990 NULL, NULL);
1991 set_next_passphrase( NULL );
1992 assert( dek );
1993 memset( r->u.value, 0, strlen(r->u.value) );
1995 r = xcalloc (1, sizeof *r );
1996 r->key = pPASSPHRASE_S2K;
1997 r->u.s2k = s2k;
1998 r->next = para;
1999 para = r;
2000 r = xcalloc (1, sizeof *r );
2001 r->key = pPASSPHRASE_DEK;
2002 r->u.dek = dek;
2003 r->next = para;
2004 para = r;
2007 /* make KEYEXPIRE from Expire-Date */
2008 r = get_parameter( para, pEXPIREDATE );
2009 if( r && *r->u.value ) {
2010 i = parse_expire_string( r->u.value );
2011 if( i < 0 ) {
2012 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2013 return -1;
2015 r->u.expire = i * 86400L;
2016 r->key = pKEYEXPIRE; /* change hat entry */
2017 /* also set it for the subkey */
2018 r = xcalloc (1, sizeof *r + 20 );
2019 r->key = pSUBKEYEXPIRE;
2020 r->u.expire = i * 86400L;
2021 r->next = para;
2022 para = r;
2025 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2026 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2027 return -1;
2030 do_generate_keypair( para, outctrl, card);
2031 return 0;
2035 /****************
2036 * Kludge to allow non interactive key generation controlled
2037 * by a parameter file (which currently is only stdin)
2038 * Note, that string parameters are expected to be in UTF-8
2040 static void
2041 read_parameter_file( const char *fname )
2043 static struct { const char *name;
2044 enum para_name key;
2045 } keywords[] = {
2046 { "Key-Type", pKEYTYPE},
2047 { "Key-Length", pKEYLENGTH },
2048 { "Key-Usage", pKEYUSAGE },
2049 { "Subkey-Type", pSUBKEYTYPE },
2050 { "Subkey-Length", pSUBKEYLENGTH },
2051 { "Subkey-Usage", pSUBKEYUSAGE },
2052 { "Name-Real", pNAMEREAL },
2053 { "Name-Email", pNAMEEMAIL },
2054 { "Name-Comment", pNAMECOMMENT },
2055 { "Expire-Date", pEXPIREDATE },
2056 { "Passphrase", pPASSPHRASE },
2057 { "Preferences", pPREFERENCES },
2058 { "Revoker", pREVOKER },
2059 { NULL, 0 }
2061 FILE *fp;
2062 char line[1024], *p;
2063 int lnr;
2064 const char *err = NULL;
2065 struct para_data_s *para, *r;
2066 int i;
2067 struct output_control_s outctrl;
2069 memset( &outctrl, 0, sizeof( outctrl ) );
2071 if( !fname || !*fname || !strcmp(fname,"-") ) {
2072 fp = stdin;
2073 fname = "-";
2075 else {
2076 fp = fopen( fname, "r" );
2077 if( !fp ) {
2078 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
2079 return;
2083 lnr = 0;
2084 err = NULL;
2085 para = NULL;
2086 while( fgets( line, DIM(line)-1, fp ) ) {
2087 char *keyword, *value;
2089 lnr++;
2090 if( *line && line[strlen(line)-1] != '\n' ) {
2091 err = "line too long";
2092 break;
2094 for( p = line; isspace(*(byte*)p); p++ )
2096 if( !*p || *p == '#' )
2097 continue;
2098 keyword = p;
2099 if( *keyword == '%' ) {
2100 for( ; !isspace(*(byte*)p); p++ )
2102 if( *p )
2103 *p++ = 0;
2104 for( ; isspace(*(byte*)p); p++ )
2106 value = p;
2107 trim_trailing_ws( value, strlen(value) );
2108 if( !ascii_strcasecmp( keyword, "%echo" ) )
2109 log_info("%s\n", value );
2110 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2111 outctrl.dryrun = 1;
2112 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2113 outctrl.lnr = lnr;
2114 proc_parameter_file( para, fname, &outctrl, 0 );
2115 release_parameter_list( para );
2116 para = NULL;
2118 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2119 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2120 ; /* still the same file - ignore it */
2121 else {
2122 xfree ( outctrl.pub.newfname );
2123 outctrl.pub.newfname = xstrdup ( value );
2124 outctrl.use_files = 1;
2127 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2128 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2129 ; /* still the same file - ignore it */
2130 else {
2131 xfree ( outctrl.sec.newfname );
2132 outctrl.sec.newfname = xstrdup ( value );
2133 outctrl.use_files = 1;
2136 else
2137 log_info("skipping control `%s' (%s)\n", keyword, value );
2140 continue;
2144 if( !(p = strchr( p, ':' )) || p == keyword ) {
2145 err = "missing colon";
2146 break;
2148 if( *p )
2149 *p++ = 0;
2150 for( ; isspace(*(byte*)p); p++ )
2152 if( !*p ) {
2153 err = "missing argument";
2154 break;
2156 value = p;
2157 trim_trailing_ws( value, strlen(value) );
2159 for(i=0; keywords[i].name; i++ ) {
2160 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2161 break;
2163 if( !keywords[i].name ) {
2164 err = "unknown keyword";
2165 break;
2167 if( keywords[i].key != pKEYTYPE && !para ) {
2168 err = "parameter block does not start with \"Key-Type\"";
2169 break;
2172 if( keywords[i].key == pKEYTYPE && para ) {
2173 outctrl.lnr = lnr;
2174 proc_parameter_file( para, fname, &outctrl, 0 );
2175 release_parameter_list( para );
2176 para = NULL;
2178 else {
2179 for( r = para; r; r = r->next ) {
2180 if( r->key == keywords[i].key )
2181 break;
2183 if( r ) {
2184 err = "duplicate keyword";
2185 break;
2188 r = xcalloc (1, sizeof *r + strlen( value ) );
2189 r->lnr = lnr;
2190 r->key = keywords[i].key;
2191 strcpy( r->u.value, value );
2192 r->next = para;
2193 para = r;
2195 if( err )
2196 log_error("%s:%d: %s\n", fname, lnr, err );
2197 else if( ferror(fp) ) {
2198 log_error("%s:%d: read error: %s\n", fname, lnr, strerror(errno) );
2200 else if( para ) {
2201 outctrl.lnr = lnr;
2202 proc_parameter_file( para, fname, &outctrl, 0 );
2205 if( outctrl.use_files ) { /* close open streams */
2206 iobuf_close( outctrl.pub.stream );
2207 iobuf_close( outctrl.sec.stream );
2208 xfree ( outctrl.pub.fname );
2209 xfree ( outctrl.pub.newfname );
2210 xfree ( outctrl.sec.fname );
2211 xfree ( outctrl.sec.newfname );
2214 release_parameter_list( para );
2215 if( strcmp( fname, "-" ) )
2216 fclose(fp);
2220 /****************
2221 * Generate a keypair (fname is only used in batch mode) If
2222 * CARD_SERIALNO is not NULL the fucntion will create the keys on an
2223 * OpenPGP Card.
2225 void
2226 generate_keypair( const char *fname, const char *card_serialno )
2228 unsigned int nbits;
2229 char *uid = NULL;
2230 DEK *dek;
2231 STRING2KEY *s2k;
2232 int algo;
2233 unsigned int use;
2234 int both = 0;
2235 u32 expire;
2236 struct para_data_s *para = NULL;
2237 struct para_data_s *r;
2238 struct output_control_s outctrl;
2240 memset (&outctrl, 0, sizeof (outctrl));
2242 if (opt.batch && card_serialno)
2244 /* We don't yet support unattended key generation. */
2245 log_error (_("sorry, can't do this in batch mode\n"));
2246 return;
2249 if (opt.batch)
2251 read_parameter_file( fname );
2252 return;
2255 if (card_serialno)
2257 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
2258 r->key = pSERIALNO;
2259 strcpy( r->u.value, card_serialno);
2260 r->next = para;
2261 para = r;
2263 algo = PUBKEY_ALGO_RSA;
2265 r = xcalloc (1, sizeof *r + 20 );
2266 r->key = pKEYTYPE;
2267 sprintf( r->u.value, "%d", algo );
2268 r->next = para;
2269 para = r;
2270 r = xcalloc (1, sizeof *r + 20 );
2271 r->key = pKEYUSAGE;
2272 strcpy (r->u.value, "sign");
2273 r->next = para;
2274 para = r;
2276 r = xcalloc (1, sizeof *r + 20 );
2277 r->key = pSUBKEYTYPE;
2278 sprintf( r->u.value, "%d", algo );
2279 r->next = para;
2280 para = r;
2281 r = xcalloc (1, sizeof *r + 20 );
2282 r->key = pSUBKEYUSAGE;
2283 strcpy (r->u.value, "encrypt");
2284 r->next = para;
2285 para = r;
2287 r = xcalloc (1, sizeof *r + 20 );
2288 r->key = pAUTHKEYTYPE;
2289 sprintf( r->u.value, "%d", algo );
2290 r->next = para;
2291 para = r;
2293 else
2295 algo = ask_algo (0, &use);
2297 if (!algo)
2298 { /* default: DSA with ElG subkey of the specified size */
2299 both = 1;
2300 r = xcalloc (1, sizeof *r + 20 );
2301 r->key = pKEYTYPE;
2302 sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
2303 r->next = para;
2304 para = r;
2305 tty_printf(_("DSA keypair will have 1024 bits.\n"));
2306 r = xcalloc (1, sizeof *r + 20 );
2307 r->key = pKEYLENGTH;
2308 strcpy( r->u.value, "1024" );
2309 r->next = para;
2310 para = r;
2311 r = xcalloc (1, sizeof *r + 20 );
2312 r->key = pKEYUSAGE;
2313 strcpy( r->u.value, "sign" );
2314 r->next = para;
2315 para = r;
2317 algo = PUBKEY_ALGO_ELGAMAL_E;
2318 r = xcalloc (1, sizeof *r + 20 );
2319 r->key = pSUBKEYTYPE;
2320 sprintf( r->u.value, "%d", algo );
2321 r->next = para;
2322 para = r;
2323 r = xcalloc (1, sizeof *r + 20 );
2324 r->key = pSUBKEYUSAGE;
2325 strcpy( r->u.value, "encrypt" );
2326 r->next = para;
2327 r->next = para;
2328 para = r;
2330 else
2332 r = xcalloc (1, sizeof *r + 20 );
2333 r->key = pKEYTYPE;
2334 sprintf( r->u.value, "%d", algo );
2335 r->next = para;
2336 para = r;
2338 if (use)
2340 r = xcalloc (1, sizeof *r + 20 );
2341 r->key = pKEYUSAGE;
2342 sprintf( r->u.value, "%s%s",
2343 (use & PUBKEY_USAGE_SIG)? "sign ":"",
2344 (use & PUBKEY_USAGE_ENC)? "encrypt ":"" );
2345 r->next = para;
2346 para = r;
2350 nbits = ask_keysize( algo );
2351 r = xcalloc (1, sizeof *r + 20 );
2352 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
2353 sprintf( r->u.value, "%u", nbits);
2354 r->next = para;
2355 para = r;
2358 expire = ask_expire_interval(0);
2359 r = xcalloc (1, sizeof *r + 20 );
2360 r->key = pKEYEXPIRE;
2361 r->u.expire = expire;
2362 r->next = para;
2363 para = r;
2364 r = xcalloc (1, sizeof *r + 20 );
2365 r->key = pSUBKEYEXPIRE;
2366 r->u.expire = expire;
2367 r->next = para;
2368 para = r;
2370 uid = ask_user_id(0);
2371 if (!uid)
2373 log_error(_("Key generation canceled.\n"));
2374 release_parameter_list( para );
2375 return;
2377 r = xcalloc (1, sizeof *r + strlen(uid) );
2378 r->key = pUSERID;
2379 strcpy( r->u.value, uid );
2380 r->next = para;
2381 para = r;
2383 dek = card_serialno? NULL : ask_passphrase( &s2k );
2384 if (dek)
2386 r = xcalloc (1, sizeof *r );
2387 r->key = pPASSPHRASE_DEK;
2388 r->u.dek = dek;
2389 r->next = para;
2390 para = r;
2391 r = xcalloc (1, sizeof *r );
2392 r->key = pPASSPHRASE_S2K;
2393 r->u.s2k = s2k;
2394 r->next = para;
2395 para = r;
2398 proc_parameter_file (para, "[internal]", &outctrl, !!card_serialno);
2399 release_parameter_list (para);
2403 static void
2404 print_status_key_created (int letter, PKT_public_key *pk)
2406 byte array[MAX_FINGERPRINT_LEN], *s;
2407 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
2408 size_t i, n;
2410 p = buf;
2411 *p++ = letter;
2412 *p++ = ' ';
2413 fingerprint_from_pk (pk, array, &n);
2414 s = array;
2415 for (i=0; i < n ; i++, s++, p += 2)
2416 sprintf (p, "%02X", *s);
2417 *p = 0;
2418 write_status_text (STATUS_KEY_CREATED, buf);
2423 static void
2424 do_generate_keypair (struct para_data_s *para,
2425 struct output_control_s *outctrl, int card)
2427 KBNODE pub_root = NULL;
2428 KBNODE sec_root = NULL;
2429 PKT_secret_key *sk = NULL;
2430 const char *s;
2431 struct revocation_key *revkey;
2432 int rc;
2433 int did_sub = 0;
2435 if (outctrl->dryrun)
2437 log_info ("dry-run mode - key generation skipped\n");
2438 return;
2442 if (outctrl->use_files)
2444 if (outctrl->pub.newfname)
2446 iobuf_close (outctrl->pub.stream);
2447 outctrl->pub.stream = NULL;
2448 xfree (outctrl->pub.fname);
2449 outctrl->pub.fname = outctrl->pub.newfname;
2450 outctrl->pub.newfname = NULL;
2452 outctrl->pub.stream = iobuf_create (outctrl->pub.fname);
2453 if (!outctrl->pub.stream)
2455 log_error ("can't create `%s': %s\n", outctrl->pub.fname,
2456 strerror (errno));
2457 return;
2459 if (opt.armor)
2461 outctrl->pub.afx.what = 1;
2462 iobuf_push_filter (outctrl->pub.stream, armor_filter,
2463 &outctrl->pub.afx);
2466 if (outctrl->sec.newfname)
2468 iobuf_close (outctrl->sec.stream);
2469 outctrl->sec.stream = NULL;
2470 xfree (outctrl->sec.fname);
2471 outctrl->sec.fname = outctrl->sec.newfname;
2472 outctrl->sec.newfname = NULL;
2474 outctrl->sec.stream = iobuf_create (outctrl->sec.fname);
2475 if (!outctrl->sec.stream)
2477 log_error ("can't create `%s': %s\n", outctrl->sec.fname,
2478 strerror (errno));
2479 return;
2481 if (opt.armor)
2483 outctrl->sec.afx.what = 5;
2484 iobuf_push_filter (outctrl->sec.stream, armor_filter,
2485 &outctrl->sec.afx);
2488 assert (outctrl->pub.stream);
2489 assert (outctrl->sec.stream);
2490 if (opt.verbose)
2492 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname);
2493 if (card)
2494 log_info (_("writing secret key stub to `%s'\n"),
2495 outctrl->sec.fname);
2496 else
2497 log_info (_("writing secret key to `%s'\n"), outctrl->sec.fname);
2502 /* We create the packets as a tree of kbnodes. Because the structure
2503 * we create is known in advance we simply generate a linked list.
2504 * The first packet is a dummy comment packet which we flag
2505 * as deleted. The very first packet must always be a KEY packet.
2507 pub_root = make_comment_node ("#");
2508 delete_kbnode (pub_root);
2509 sec_root = make_comment_node ("#");
2510 delete_kbnode (sec_root);
2511 if (!card)
2513 rc = do_create (get_parameter_algo (para, pKEYTYPE),
2514 get_parameter_uint (para, pKEYLENGTH),
2515 pub_root, sec_root,
2516 get_parameter_dek (para, pPASSPHRASE_DEK),
2517 get_parameter_s2k (para, pPASSPHRASE_S2K),
2518 &sk, get_parameter_u32 (para, pKEYEXPIRE));
2520 else
2522 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, pub_root, sec_root,
2523 get_parameter_u32 (para, pKEYEXPIRE), para);
2524 if (!rc)
2526 sk = sec_root->next->pkt->pkt.secret_key;
2527 assert (sk);
2532 if (!rc && (revkey = get_parameter_revkey (para, pREVOKER)))
2534 rc = write_direct_sig (pub_root, pub_root, sk, revkey);
2535 if (!rc)
2536 write_direct_sig (sec_root, pub_root, sk, revkey);
2539 if (!rc && (s = get_parameter_value (para, pUSERID)))
2541 write_uid (pub_root, s);
2542 if (!rc)
2543 write_uid (sec_root, s);
2544 if (!rc)
2545 rc = write_selfsig (pub_root, pub_root, sk,
2546 get_parameter_uint (para, pKEYUSAGE));
2547 if (!rc)
2548 rc = write_selfsig (sec_root, pub_root, sk,
2549 get_parameter_uint (para, pKEYUSAGE));
2552 if ((! rc) && get_parameter (para, pSUBKEYTYPE))
2554 if (!card)
2556 rc = do_create (get_parameter_algo (para, pSUBKEYTYPE),
2557 get_parameter_uint (para, pSUBKEYLENGTH),
2558 pub_root, sec_root,
2559 get_parameter_dek (para, pPASSPHRASE_DEK),
2560 get_parameter_s2k (para, pPASSPHRASE_S2K),
2561 NULL, get_parameter_u32 (para, pSUBKEYEXPIRE));
2563 else
2565 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, pub_root, sec_root,
2566 get_parameter_u32 (para, pKEYEXPIRE), para);
2569 if (!rc)
2570 rc = write_keybinding (pub_root, pub_root, sk,
2571 get_parameter_uint (para, pSUBKEYUSAGE));
2572 if (!rc)
2573 rc = write_keybinding (sec_root, pub_root, sk,
2574 get_parameter_uint (para, pSUBKEYUSAGE));
2575 did_sub = 1;
2578 if ((! rc) && card && get_parameter (para, pAUTHKEYTYPE))
2580 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, pub_root, sec_root,
2581 get_parameter_u32 (para, pKEYEXPIRE), para);
2583 if (!rc)
2584 rc = write_keybinding (pub_root, pub_root, sk, PUBKEY_USAGE_AUTH);
2585 if (!rc)
2586 rc = write_keybinding (sec_root, pub_root, sk, PUBKEY_USAGE_AUTH);
2590 if (!rc && outctrl->use_files)
2591 { /* direct write to specified files */
2592 rc = write_keyblock (outctrl->pub.stream, pub_root);
2593 if (rc)
2594 log_error ("can't write public key: %s\n", gpg_strerror (rc));
2595 if (!rc)
2597 rc = write_keyblock (outctrl->sec.stream, sec_root);
2598 if (rc)
2599 log_error ("can't write secret key: %s\n", gpg_strerror (rc));
2603 else if (!rc)
2604 { /* write to the standard keyrings */
2605 KEYDB_HANDLE pub_hd = keydb_new (0);
2606 KEYDB_HANDLE sec_hd = keydb_new (1);
2608 /* FIXME: we may have to create the keyring first */
2609 rc = keydb_locate_writable (pub_hd, NULL);
2610 if (rc)
2611 log_error (_("no writable public keyring found: %s\n"),
2612 gpg_strerror (rc));
2614 if (!rc)
2616 rc = keydb_locate_writable (sec_hd, NULL);
2617 if (rc)
2618 log_error (_("no writable secret keyring found: %s\n"),
2619 gpg_strerror (rc));
2622 if (!rc && opt.verbose)
2624 log_info (_("writing public key to `%s'\n"),
2625 keydb_get_resource_name (pub_hd));
2626 if (card)
2627 log_info (_("writing secret key stub to `%s'\n"),
2628 keydb_get_resource_name (sec_hd));
2629 else
2630 log_info (_("writing secret key to `%s'\n"),
2631 keydb_get_resource_name (sec_hd));
2634 if (!rc)
2636 rc = keydb_insert_keyblock (pub_hd, pub_root);
2637 if (rc)
2638 log_error (_("error writing public keyring `%s': %s\n"),
2639 keydb_get_resource_name (pub_hd), gpg_strerror (rc));
2642 if (!rc)
2644 rc = keydb_insert_keyblock (sec_hd, sec_root);
2645 if (rc)
2646 log_error (_("error writing secret keyring `%s': %s\n"),
2647 keydb_get_resource_name (pub_hd), gpg_strerror (rc));
2650 keydb_release (pub_hd);
2651 keydb_release (sec_hd);
2653 if (!rc)
2655 int no_enc_rsa =
2656 get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
2657 && get_parameter_uint (para, pKEYUSAGE)
2658 && !(get_parameter_uint (para, pKEYUSAGE) & PUBKEY_USAGE_ENC);
2659 PKT_public_key *pk = find_kbnode (pub_root,
2660 PKT_PUBLIC_KEY)->pkt->pkt.
2661 public_key;
2663 update_ownertrust (pk,
2664 ((get_ownertrust (pk) & ~TRUST_MASK)
2665 | TRUST_ULTIMATE));
2667 if (!opt.batch)
2669 tty_printf (_("public and secret key created and signed.\n"));
2670 tty_printf (_("key marked as ultimately trusted.\n"));
2671 tty_printf ("\n");
2672 list_keyblock (pub_root, 0, 1, NULL);
2676 if (!opt.batch
2677 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
2678 || no_enc_rsa) && !get_parameter (para, pSUBKEYTYPE))
2680 tty_printf (_("Note that this key cannot be used for "
2681 "encryption. You may want to use\n"
2682 "the command \"--edit-key\" to generate a "
2683 "secondary key for this purpose.\n"));
2686 if (!opt.batch && card)
2688 tty_printf(_(
2689 "Please create a revocation certificate now, so that you are able\n"
2690 "to revoke the key if it ever happens that you lose your card or\n"
2691 "the card gets damaged. Use the command \"--gen-revoke\".\n"
2697 if (rc)
2699 if (opt.batch)
2700 log_error ("key generation failed: %s\n", gpg_strerror (rc));
2701 else
2702 tty_printf (_("Key generation failed: %s\n"), gpg_strerror (rc));
2704 else
2706 PKT_public_key *pk = find_kbnode (pub_root,
2707 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
2708 print_status_key_created (did_sub ? 'B' : 'P', pk);
2711 release_kbnode (pub_root);
2712 release_kbnode (sec_root);
2713 if (sk && !card) /* The unprotected secret key unless we have */
2714 free_secret_key (sk); /* a shallow copy in card mode. */
2718 /****************
2719 * add a new subkey to an existing key.
2720 * Returns true if a new key has been generated and put into the keyblocks.
2723 generate_subkeypair( KBNODE pub_keyblock, KBNODE sec_keyblock )
2725 int okay=0, rc=0;
2726 KBNODE node;
2727 PKT_secret_key *sk = NULL; /* this is the primary sk */
2728 int algo;
2729 unsigned int use;
2730 u32 expire;
2731 unsigned nbits;
2732 char *passphrase = NULL;
2733 DEK *dek = NULL;
2734 STRING2KEY *s2k = NULL;
2735 u32 cur_time;
2737 /* break out the primary secret key */
2738 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
2739 if( !node ) {
2740 log_error("Oops; secret key not found anymore!\n");
2741 goto leave;
2744 /* make a copy of the sk to keep the protected one in the keyblock */
2745 sk = copy_secret_key( NULL, node->pkt->pkt.secret_key );
2747 cur_time = make_timestamp();
2748 if( sk->timestamp > cur_time ) {
2749 ulong d = sk->timestamp - cur_time;
2750 log_info( d==1 ? _("key has been created %lu second "
2751 "in future (time warp or clock problem)\n")
2752 : _("key has been created %lu seconds "
2753 "in future (time warp or clock problem)\n"), d );
2754 if( !opt.ignore_time_conflict ) {
2755 rc = GPG_ERR_TIME_CONFLICT;
2756 goto leave;
2760 if (sk->version < 4) {
2761 log_info (_("NOTE: creating subkeys for v3 keys "
2762 "is not OpenPGP compliant\n"));
2763 goto leave;
2766 /* unprotect to get the passphrase */
2767 switch( is_secret_key_protected( sk ) ) {
2768 case -1:
2769 rc = GPG_ERR_PUBKEY_ALGO;
2770 break;
2771 case 0:
2772 tty_printf("This key is not protected.\n");
2773 break;
2774 default:
2775 tty_printf("Key is protected.\n");
2776 rc = check_secret_key( sk, 0 );
2777 if( !rc )
2778 passphrase = get_last_passphrase();
2779 break;
2781 if( rc )
2782 goto leave;
2785 algo = ask_algo( 1, &use );
2786 assert(algo);
2787 nbits = ask_keysize( algo );
2788 expire = ask_expire_interval(0);
2789 if( !cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
2790 _("Really create? ") ) )
2791 goto leave;
2793 if( passphrase ) {
2794 s2k = xmalloc_secure ( sizeof *s2k );
2795 s2k->mode = opt.s2k_mode;
2796 s2k->hash_algo = opt.s2k_digest_algo;
2797 set_next_passphrase( passphrase );
2798 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2799 NULL, NULL );
2802 rc = do_create( algo, nbits, pub_keyblock, sec_keyblock,
2803 dek, s2k, NULL, expire );
2804 if( !rc )
2805 rc = write_keybinding(pub_keyblock, pub_keyblock, sk, use);
2806 if( !rc )
2807 rc = write_keybinding(sec_keyblock, pub_keyblock, sk, use);
2808 if( !rc ) {
2809 okay = 1;
2810 write_status_text (STATUS_KEY_CREATED, "S");
2813 leave:
2814 if( rc )
2815 log_error(_("Key generation failed: %s\n"), gpg_strerror (rc) );
2816 xfree ( passphrase );
2817 xfree ( dek );
2818 xfree ( s2k );
2819 if( sk ) /* release the copy of the (now unprotected) secret key */
2820 free_secret_key(sk);
2821 set_next_passphrase( NULL );
2822 return okay;
2825 /****************
2826 * Write a keyblock to an output stream
2828 static int
2829 write_keyblock( iobuf_t out, KBNODE node )
2831 for( ; node ; node = node->next ) {
2832 int rc = build_packet( out, node->pkt );
2833 if( rc ) {
2834 log_error("build_packet(%d) failed: %s\n",
2835 node->pkt->pkttype, gpg_strerror (rc) );
2836 return rc;
2839 return 0;
2844 static int
2845 gen_card_key (int algo, int keyno, KBNODE pub_root, KBNODE sec_root,
2846 u32 expireval, struct para_data_s *para)
2848 int rc;
2849 const char *s;
2850 struct agent_card_genkey_s info;
2851 PACKET *pkt;
2852 PKT_secret_key *sk;
2853 PKT_public_key *pk;
2855 assert (algo == PUBKEY_ALGO_RSA);
2857 rc = agent_scd_genkey (&info, keyno, 1);
2858 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
2859 /* { */
2860 /* tty_printf ("\n"); */
2861 /* log_error ("WARNING: key does already exists!\n"); */
2862 /* tty_printf ("\n"); */
2863 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
2864 /* _("Replace existing key? "))) */
2865 /* rc = agent_scd_genkey (&info, keyno, 1); */
2866 /* } */
2868 if (rc)
2869 return rc;
2871 if ( !info.n || !info.e )
2873 log_error ("communication error with SCD\n");
2874 gcry_mpi_release (info.n);
2875 gcry_mpi_release (info.e);
2876 return gpg_error (GPG_ERR_GENERAL);
2880 pk = xcalloc (1, sizeof *pk );
2881 sk = xcalloc (1, sizeof *sk );
2882 sk->timestamp = pk->timestamp = info.created_at;
2883 sk->version = pk->version = 4;
2884 if (expireval)
2885 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
2886 sk->pubkey_algo = pk->pubkey_algo = algo;
2887 pk->pkey[0] = info.n;
2888 pk->pkey[1] = info.e;
2889 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
2890 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
2891 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
2892 sk->is_protected = 1;
2893 sk->protect.s2k.mode = 1002;
2894 s = get_parameter_value (para, pSERIALNO);
2895 if (s)
2897 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
2898 sk->protect.ivlen++, s += 2)
2899 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
2902 pkt = xcalloc (1,sizeof *pkt);
2903 pkt->pkttype = keyno == 1 ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
2904 pkt->pkt.public_key = pk;
2905 add_kbnode(pub_root, new_kbnode( pkt ));
2907 pkt = xcalloc (1,sizeof *pkt);
2908 pkt->pkttype = keyno == 1 ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
2909 pkt->pkt.secret_key = sk;
2910 add_kbnode(sec_root, new_kbnode( pkt ));
2912 return 0;