Fix possible system freeze on Mac OS X.
[gnupg.git] / g10 / keygen.c
blob1be65c42ed004a99b3739b223904112041c220a1
1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007 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/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
32 #include "gpg.h"
33 #include "util.h"
34 #include "main.h"
35 #include "packet.h"
36 #include "cipher.h"
37 #include "ttyio.h"
38 #include "options.h"
39 #include "keydb.h"
40 #include "trustdb.h"
41 #include "status.h"
42 #include "i18n.h"
43 #include "keyserver-internal.h"
44 #include "call-agent.h"
47 #define MAX_PREFS 30
49 enum para_name {
50 pKEYTYPE,
51 pKEYLENGTH,
52 pKEYUSAGE,
53 pSUBKEYTYPE,
54 pSUBKEYLENGTH,
55 pSUBKEYUSAGE,
56 pAUTHKEYTYPE,
57 pNAMEREAL,
58 pNAMEEMAIL,
59 pNAMECOMMENT,
60 pPREFERENCES,
61 pREVOKER,
62 pUSERID,
63 pCREATIONDATE,
64 pKEYCREATIONDATE, /* Same in seconds since epoch. */
65 pEXPIREDATE,
66 pKEYEXPIRE, /* in n seconds */
67 pSUBKEYEXPIRE, /* in n seconds */
68 pPASSPHRASE,
69 pPASSPHRASE_DEK,
70 pPASSPHRASE_S2K,
71 pSERIALNO,
72 pBACKUPENCDIR,
73 pHANDLE,
74 pKEYSERVER
77 struct para_data_s {
78 struct para_data_s *next;
79 int lnr;
80 enum para_name key;
81 union {
82 DEK *dek;
83 STRING2KEY *s2k;
84 u32 expire;
85 u32 creation;
86 unsigned int usage;
87 struct revocation_key revkey;
88 char value[1];
89 } u;
92 struct output_control_s {
93 int lnr;
94 int dryrun;
95 int ask_passphrase;
96 int use_files;
97 struct {
98 char *fname;
99 char *newfname;
100 IOBUF stream;
101 armor_filter_context_t *afx;
102 } pub;
103 struct {
104 char *fname;
105 char *newfname;
106 IOBUF stream;
107 armor_filter_context_t *afx;
108 } sec;
112 struct opaque_data_usage_and_pk {
113 unsigned int usage;
114 PKT_public_key *pk;
118 static int prefs_initialized = 0;
119 static byte sym_prefs[MAX_PREFS];
120 static int nsym_prefs;
121 static byte hash_prefs[MAX_PREFS];
122 static int nhash_prefs;
123 static byte zip_prefs[MAX_PREFS];
124 static int nzip_prefs;
125 static int mdc_available,ks_modify;
127 static void do_generate_keypair( struct para_data_s *para,
128 struct output_control_s *outctrl, int card );
129 static int write_keyblock( IOBUF out, KBNODE node );
130 static int gen_card_key (int algo, int keyno, int is_primary,
131 KBNODE pub_root, KBNODE sec_root,
132 PKT_secret_key **ret_sk,
133 u32 *timestamp,
134 u32 expireval, struct para_data_s *para);
135 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
136 KBNODE pub_root, KBNODE sec_root,
137 u32 timestamp,
138 u32 expireval, struct para_data_s *para,
139 const char *backup_dir);
142 static void
143 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
145 byte array[MAX_FINGERPRINT_LEN], *s;
146 char *buf, *p;
147 size_t i, n;
149 if (!handle)
150 handle = "";
152 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
154 p = buf;
155 if (letter || pk)
157 *p++ = letter;
158 *p++ = ' ';
159 fingerprint_from_pk (pk, array, &n);
160 s = array;
161 for (i=0; i < n ; i++, s++, p += 2)
162 sprintf (p, "%02X", *s);
164 if (*handle)
166 *p++ = ' ';
167 for (i=0; handle[i] && i < 100; i++)
168 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
170 *p = 0;
171 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
172 buf);
173 xfree (buf);
176 static void
177 print_status_key_not_created (const char *handle)
179 print_status_key_created (0, NULL, handle);
184 static void
185 write_uid( KBNODE root, const char *s )
187 PACKET *pkt = xmalloc_clear(sizeof *pkt );
188 size_t n = strlen(s);
190 pkt->pkttype = PKT_USER_ID;
191 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
192 pkt->pkt.user_id->len = n;
193 pkt->pkt.user_id->ref = 1;
194 strcpy(pkt->pkt.user_id->name, s);
195 add_kbnode( root, new_kbnode( pkt ) );
198 static void
199 do_add_key_flags (PKT_signature *sig, unsigned int use)
201 byte buf[1];
203 buf[0] = 0;
205 /* The spec says that all primary keys MUST be able to certify. */
206 if(sig->sig_class!=0x18)
207 buf[0] |= 0x01;
209 if (use & PUBKEY_USAGE_SIG)
210 buf[0] |= 0x02;
211 if (use & PUBKEY_USAGE_ENC)
212 buf[0] |= 0x04 | 0x08;
213 if (use & PUBKEY_USAGE_AUTH)
214 buf[0] |= 0x20;
216 if (!buf[0])
217 return;
219 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
224 keygen_add_key_expire( PKT_signature *sig, void *opaque )
226 PKT_public_key *pk = opaque;
227 byte buf[8];
228 u32 u;
230 if( pk->expiredate ) {
231 if(pk->expiredate > pk->timestamp)
232 u= pk->expiredate - pk->timestamp;
233 else
234 u= 1;
236 buf[0] = (u >> 24) & 0xff;
237 buf[1] = (u >> 16) & 0xff;
238 buf[2] = (u >> 8) & 0xff;
239 buf[3] = u & 0xff;
240 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
242 else
244 /* Make sure we don't leave a key expiration subpacket lying
245 around */
246 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
249 return 0;
252 static int
253 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
255 struct opaque_data_usage_and_pk *oduap = opaque;
257 do_add_key_flags (sig, oduap->usage);
258 return keygen_add_key_expire (sig, oduap->pk);
261 static int
262 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
264 int i;
266 for (i=0; i < *nbuf; i++ )
267 if (buf[i] == val)
269 log_info (_("preference `%s' duplicated\n"), item);
270 return -1;
273 if (*nbuf >= MAX_PREFS)
275 if(type==1)
276 log_info(_("too many cipher preferences\n"));
277 else if(type==2)
278 log_info(_("too many digest preferences\n"));
279 else if(type==3)
280 log_info(_("too many compression preferences\n"));
281 else
282 BUG();
284 return -1;
287 buf[(*nbuf)++] = val;
288 return 0;
292 * Parse the supplied string and use it to set the standard
293 * preferences. The string may be in a form like the one printed by
294 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
295 * cipher/hash/compress names. Use NULL to set the default
296 * preferences. Returns: 0 = okay
299 keygen_set_std_prefs (const char *string,int personal)
301 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
302 int nsym=0, nhash=0, nzip=0, val, rc=0;
303 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
304 char dummy_string[45+1]; /* Enough for 15 items. */
306 if (!string || !ascii_strcasecmp (string, "default"))
308 if (opt.def_preference_list)
309 string=opt.def_preference_list;
310 else
312 dummy_string[0]='\0';
314 /* The rationale why we use the order AES256,192,128 is
315 for compatibility reasons with PGP. If gpg would
316 define AES128 first, we would get the somewhat
317 confusing situation:
319 gpg -r pgpkey -r gpgkey ---gives--> AES256
320 gpg -r gpgkey -r pgpkey ---gives--> AES
322 Note that by using --personal-cipher-preferences it is
323 possible to prefer AES128.
326 /* Make sure we do not add more than 15 items here, as we
327 could overflow the size of dummy_string. We currently
328 have at most 12. */
329 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
330 strcat(dummy_string,"S9 ");
331 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
332 strcat(dummy_string,"S8 ");
333 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
334 strcat(dummy_string,"S7 ");
335 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
336 strcat(dummy_string,"S3 ");
337 strcat(dummy_string,"S2 "); /* 3DES */
338 /* If we have it, IDEA goes *after* 3DES so it won't be
339 used unless we're encrypting along with a V3 key.
340 Ideally, we would only put the S1 preference in if the
341 key was RSA and <=2048 bits, as that is what won't
342 break PGP2, but that is difficult with the current
343 code, and not really worth checking as a non-RSA <=2048
344 bit key wouldn't be usable by PGP2 anyway. -dms */
345 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
346 strcat(dummy_string,"S1 ");
348 /* SHA-1 */
349 strcat(dummy_string,"H2 ");
351 if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256))
352 strcat(dummy_string,"H8 ");
354 /* RIPEMD160 */
355 if (!openpgp_md_test_algo(DIGEST_ALGO_RMD160))
356 strcat(dummy_string,"H3 ");
358 /* ZLIB */
359 strcat(dummy_string,"Z2 ");
361 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
362 strcat(dummy_string,"Z3 ");
364 /* ZIP */
365 strcat(dummy_string,"Z1");
367 string=dummy_string;
370 else if (!ascii_strcasecmp (string, "none"))
371 string = "";
373 if(strlen(string))
375 char *tok,*prefstring;
377 prefstring=xstrdup(string); /* need a writable string! */
379 while((tok=strsep(&prefstring," ,")))
381 if((val=string_to_cipher_algo (tok)))
383 if(set_one_pref(val,1,tok,sym,&nsym))
384 rc=-1;
386 else if((val=string_to_digest_algo (tok)))
388 if(set_one_pref(val,2,tok,hash,&nhash))
389 rc=-1;
391 else if((val=string_to_compress_algo(tok))>-1)
393 if(set_one_pref(val,3,tok,zip,&nzip))
394 rc=-1;
396 else if (ascii_strcasecmp(tok,"mdc")==0)
397 mdc=1;
398 else if (ascii_strcasecmp(tok,"no-mdc")==0)
399 mdc=0;
400 else if (ascii_strcasecmp(tok,"ks-modify")==0)
401 modify=1;
402 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
403 modify=0;
404 else
406 log_info (_("invalid item `%s' in preference string\n"),tok);
408 /* Complain if IDEA is not available. */
409 if(ascii_strcasecmp(tok,"s1")==0
410 || ascii_strcasecmp(tok,"idea")==0)
411 idea_cipher_warn(1);
413 rc=-1;
417 xfree(prefstring);
420 if(!rc)
422 if(personal)
424 if(personal==PREFTYPE_SYM)
426 xfree(opt.personal_cipher_prefs);
428 if(nsym==0)
429 opt.personal_cipher_prefs=NULL;
430 else
432 int i;
434 opt.personal_cipher_prefs=
435 xmalloc(sizeof(prefitem_t *)*(nsym+1));
437 for (i=0; i<nsym; i++)
439 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
440 opt.personal_cipher_prefs[i].value = sym[i];
443 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
444 opt.personal_cipher_prefs[i].value = 0;
447 else if(personal==PREFTYPE_HASH)
449 xfree(opt.personal_digest_prefs);
451 if(nhash==0)
452 opt.personal_digest_prefs=NULL;
453 else
455 int i;
457 opt.personal_digest_prefs=
458 xmalloc(sizeof(prefitem_t *)*(nhash+1));
460 for (i=0; i<nhash; i++)
462 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
463 opt.personal_digest_prefs[i].value = hash[i];
466 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
467 opt.personal_digest_prefs[i].value = 0;
470 else if(personal==PREFTYPE_ZIP)
472 xfree(opt.personal_compress_prefs);
474 if(nzip==0)
475 opt.personal_compress_prefs=NULL;
476 else
478 int i;
480 opt.personal_compress_prefs=
481 xmalloc(sizeof(prefitem_t *)*(nzip+1));
483 for (i=0; i<nzip; i++)
485 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
486 opt.personal_compress_prefs[i].value = zip[i];
489 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
490 opt.personal_compress_prefs[i].value = 0;
494 else
496 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
497 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
498 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
499 mdc_available = mdc;
500 ks_modify = modify;
501 prefs_initialized = 1;
505 return rc;
508 /* Return a fake user ID containing the preferences. Caller must
509 free. */
510 PKT_user_id *keygen_get_std_prefs(void)
512 int i,j=0;
513 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
515 if(!prefs_initialized)
516 keygen_set_std_prefs(NULL,0);
518 uid->ref=1;
520 uid->prefs=xmalloc((sizeof(prefitem_t *)*
521 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
523 for(i=0;i<nsym_prefs;i++,j++)
525 uid->prefs[j].type=PREFTYPE_SYM;
526 uid->prefs[j].value=sym_prefs[i];
529 for(i=0;i<nhash_prefs;i++,j++)
531 uid->prefs[j].type=PREFTYPE_HASH;
532 uid->prefs[j].value=hash_prefs[i];
535 for(i=0;i<nzip_prefs;i++,j++)
537 uid->prefs[j].type=PREFTYPE_ZIP;
538 uid->prefs[j].value=zip_prefs[i];
541 uid->prefs[j].type=PREFTYPE_NONE;
542 uid->prefs[j].value=0;
544 uid->flags.mdc=mdc_available;
545 uid->flags.ks_modify=ks_modify;
547 return uid;
550 static void
551 add_feature_mdc (PKT_signature *sig,int enabled)
553 const byte *s;
554 size_t n;
555 int i;
556 char *buf;
558 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
559 /* Already set or cleared */
560 if (s && n &&
561 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
562 return;
564 if (!s || !n) { /* create a new one */
565 n = 1;
566 buf = xmalloc_clear (n);
568 else {
569 buf = xmalloc (n);
570 memcpy (buf, s, n);
573 if(enabled)
574 buf[0] |= 0x01; /* MDC feature */
575 else
576 buf[0] &= ~0x01;
578 /* Are there any bits set? */
579 for(i=0;i<n;i++)
580 if(buf[i]!=0)
581 break;
583 if(i==n)
584 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
585 else
586 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
588 xfree (buf);
591 static void
592 add_keyserver_modify (PKT_signature *sig,int enabled)
594 const byte *s;
595 size_t n;
596 int i;
597 char *buf;
599 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
600 enabled=!enabled;
602 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
603 /* Already set or cleared */
604 if (s && n &&
605 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
606 return;
608 if (!s || !n) { /* create a new one */
609 n = 1;
610 buf = xmalloc_clear (n);
612 else {
613 buf = xmalloc (n);
614 memcpy (buf, s, n);
617 if(enabled)
618 buf[0] |= 0x80; /* no-modify flag */
619 else
620 buf[0] &= ~0x80;
622 /* Are there any bits set? */
623 for(i=0;i<n;i++)
624 if(buf[i]!=0)
625 break;
627 if(i==n)
628 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
629 else
630 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
632 xfree (buf);
637 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
639 (void)opaque;
641 if (!prefs_initialized)
642 keygen_set_std_prefs (NULL, 0);
644 if (nsym_prefs)
645 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
646 else
648 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
649 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
652 if (nhash_prefs)
653 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
654 else
656 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
657 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
660 if (nzip_prefs)
661 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
662 else
664 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
665 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
668 /* Make sure that the MDC feature flag is set if needed. */
669 add_feature_mdc (sig,mdc_available);
670 add_keyserver_modify (sig,ks_modify);
671 keygen_add_keyserver_url(sig,NULL);
673 return 0;
677 /****************
678 * Add preference to the self signature packet.
679 * This is only called for packets with version > 3.
683 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
685 PKT_public_key *pk = opaque;
687 do_add_key_flags (sig, pk->pubkey_usage);
688 keygen_add_key_expire( sig, opaque );
689 keygen_upd_std_prefs (sig, opaque);
690 keygen_add_keyserver_url(sig,NULL);
692 return 0;
696 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
698 const char *url=opaque;
700 if(!url)
701 url=opt.def_keyserver_url;
703 if(url)
704 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
705 else
706 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
708 return 0;
712 keygen_add_notations(PKT_signature *sig,void *opaque)
714 struct notation *notation;
716 /* We always start clean */
717 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
718 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
719 sig->flags.notation=0;
721 for(notation=opaque;notation;notation=notation->next)
722 if(!notation->flags.ignore)
724 unsigned char *buf;
725 unsigned int n1,n2;
727 n1=strlen(notation->name);
728 if(notation->altvalue)
729 n2=strlen(notation->altvalue);
730 else if(notation->bdat)
731 n2=notation->blen;
732 else
733 n2=strlen(notation->value);
735 buf = xmalloc( 8 + n1 + n2 );
737 /* human readable or not */
738 buf[0] = notation->bdat?0:0x80;
739 buf[1] = buf[2] = buf[3] = 0;
740 buf[4] = n1 >> 8;
741 buf[5] = n1;
742 buf[6] = n2 >> 8;
743 buf[7] = n2;
744 memcpy(buf+8, notation->name, n1 );
745 if(notation->altvalue)
746 memcpy(buf+8+n1, notation->altvalue, n2 );
747 else if(notation->bdat)
748 memcpy(buf+8+n1, notation->bdat, n2 );
749 else
750 memcpy(buf+8+n1, notation->value, n2 );
751 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
752 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
753 buf, 8+n1+n2 );
754 xfree(buf);
757 return 0;
761 keygen_add_revkey(PKT_signature *sig, void *opaque)
763 struct revocation_key *revkey=opaque;
764 byte buf[2+MAX_FINGERPRINT_LEN];
766 buf[0]=revkey->class;
767 buf[1]=revkey->algid;
768 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
770 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
772 /* All sigs with revocation keys set are nonrevocable */
773 sig->flags.revocable=0;
774 buf[0] = 0;
775 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
777 parse_revkeys(sig);
779 return 0;
784 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
785 signature creation time. */
787 make_backsig (PKT_signature *sig,PKT_public_key *pk,
788 PKT_public_key *sub_pk,PKT_secret_key *sub_sk,
789 u32 timestamp)
791 PKT_signature *backsig;
792 int rc;
794 cache_public_key(sub_pk);
796 rc = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_sk, 0x19,
797 0, 0, timestamp, 0, NULL, NULL);
798 if(rc)
799 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
800 else
802 /* Get it into a binary packed form. */
803 IOBUF backsig_out=iobuf_temp();
804 PACKET backsig_pkt;
806 init_packet(&backsig_pkt);
807 backsig_pkt.pkttype=PKT_SIGNATURE;
808 backsig_pkt.pkt.signature=backsig;
809 rc=build_packet(backsig_out,&backsig_pkt);
810 free_packet(&backsig_pkt);
811 if(rc)
812 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
813 else
815 size_t pktlen=0;
816 byte *buf=iobuf_get_temp_buffer(backsig_out);
818 /* Remove the packet header */
819 if(buf[0]&0x40)
821 if(buf[1]<192)
823 pktlen=buf[1];
824 buf+=2;
826 else if(buf[1]<224)
828 pktlen=(buf[1]-192)*256;
829 pktlen+=buf[2]+192;
830 buf+=3;
832 else if(buf[1]==255)
834 pktlen =buf[2] << 24;
835 pktlen|=buf[3] << 16;
836 pktlen|=buf[4] << 8;
837 pktlen|=buf[5];
838 buf+=6;
840 else
841 BUG();
843 else
845 int mark=1;
847 switch(buf[0]&3)
849 case 3:
850 BUG();
851 break;
853 case 2:
854 pktlen =buf[mark++] << 24;
855 pktlen|=buf[mark++] << 16;
857 case 1:
858 pktlen|=buf[mark++] << 8;
860 case 0:
861 pktlen|=buf[mark++];
864 buf+=mark;
867 /* Now make the binary blob into a subpacket. */
868 build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
870 iobuf_close(backsig_out);
874 return rc;
878 static int
879 write_direct_sig (KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
880 struct revocation_key *revkey, u32 timestamp)
882 PACKET *pkt;
883 PKT_signature *sig;
884 int rc=0;
885 KBNODE node;
886 PKT_public_key *pk;
888 if( opt.verbose )
889 log_info(_("writing direct signature\n"));
891 /* Get the pk packet from the pub_tree. */
892 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
893 if( !node )
894 BUG();
895 pk = node->pkt->pkt.public_key;
897 /* We have to cache the key, so that the verification of the
898 signature creation is able to retrieve the public key. */
899 cache_public_key (pk);
901 /* Make the signature. */
902 rc = make_keysig_packet (&sig,pk,NULL,NULL,sk,0x1F,
903 0, 0, timestamp, 0,
904 keygen_add_revkey, revkey);
905 if( rc )
907 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
908 return rc;
911 pkt = xmalloc_clear( sizeof *pkt );
912 pkt->pkttype = PKT_SIGNATURE;
913 pkt->pkt.signature = sig;
914 add_kbnode( root, new_kbnode( pkt ) );
915 return rc;
919 static int
920 write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
921 unsigned int use, u32 timestamp )
923 PACKET *pkt;
924 PKT_signature *sig;
925 PKT_user_id *uid;
926 int rc=0;
927 KBNODE node;
928 PKT_public_key *pk;
930 if( opt.verbose )
931 log_info(_("writing self signature\n"));
933 /* Get the uid packet from the list. */
934 node = find_kbnode( pub_root, PKT_USER_ID );
935 if( !node )
936 BUG(); /* No user id packet in tree. */
937 uid = node->pkt->pkt.user_id;
939 /* Get the pk packet from the pub_tree. */
940 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
941 if( !node )
942 BUG();
943 pk = node->pkt->pkt.public_key;
944 pk->pubkey_usage = use;
946 /* We have to cache the key, so that the verification of the
947 signature creation is able to retrieve the public key. */
948 cache_public_key (pk);
950 /* Make the signature. */
951 rc = make_keysig_packet (&sig, pk, uid, NULL, sk, 0x13,
952 0, 0, timestamp, 0,
953 keygen_add_std_prefs, pk);
954 if( rc )
956 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
957 return rc;
960 pkt = xmalloc_clear( sizeof *pkt );
961 pkt->pkttype = PKT_SIGNATURE;
962 pkt->pkt.signature = sig;
963 add_kbnode( sec_root, new_kbnode( pkt ) );
965 pkt = xmalloc_clear( sizeof *pkt );
966 pkt->pkttype = PKT_SIGNATURE;
967 pkt->pkt.signature = copy_signature(NULL,sig);
968 add_kbnode( pub_root, new_kbnode( pkt ) );
969 return rc;
973 /* Write the key binding signature. If TIMESTAMP is not NULL use the
974 signature creation times. */
975 static int
976 write_keybinding (KBNODE root, KBNODE pub_root,
977 PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
978 unsigned int use, u32 timestamp)
980 PACKET *pkt;
981 PKT_signature *sig;
982 int rc=0;
983 KBNODE node;
984 PKT_public_key *pri_pk, *sub_pk;
985 struct opaque_data_usage_and_pk oduap;
987 if ( opt.verbose )
988 log_info(_("writing key binding signature\n"));
990 /* Get the pk packet from the pub_tree. */
991 node = find_kbnode ( pub_root, PKT_PUBLIC_KEY );
992 if ( !node )
993 BUG();
994 pri_pk = node->pkt->pkt.public_key;
996 /* We have to cache the key, so that the verification of the
997 * signature creation is able to retrieve the public key. */
998 cache_public_key (pri_pk);
1000 /* Find the last subkey. */
1001 sub_pk = NULL;
1002 for (node=pub_root; node; node = node->next )
1004 if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
1005 sub_pk = node->pkt->pkt.public_key;
1007 if (!sub_pk)
1008 BUG();
1010 /* Make the signature. */
1011 oduap.usage = use;
1012 oduap.pk = sub_pk;
1013 rc = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18,
1014 0, 0, timestamp, 0,
1015 keygen_add_key_flags_and_expire, &oduap );
1016 if (rc)
1018 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc) );
1019 return rc;
1022 /* Make a backsig. */
1023 if (use&PUBKEY_USAGE_SIG)
1025 rc = make_backsig (sig, pri_pk, sub_pk, sub_sk, timestamp);
1026 if (rc)
1027 return rc;
1030 pkt = xmalloc_clear ( sizeof *pkt );
1031 pkt->pkttype = PKT_SIGNATURE;
1032 pkt->pkt.signature = sig;
1033 add_kbnode (root, new_kbnode (pkt) );
1034 return rc;
1039 static int
1040 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1041 const char *topname, const char *elems)
1043 gcry_sexp_t list, l2;
1044 const char *s;
1045 int i, idx;
1046 int rc = 0;
1048 list = gcry_sexp_find_token (sexp, topname, 0);
1049 if (!list)
1050 return gpg_error (GPG_ERR_INV_OBJ);
1051 l2 = gcry_sexp_cadr (list);
1052 gcry_sexp_release (list);
1053 list = l2;
1054 if (!list)
1055 return gpg_error (GPG_ERR_NO_OBJ);
1057 for (idx=0,s=elems; *s; s++, idx++)
1059 l2 = gcry_sexp_find_token (list, s, 1);
1060 if (!l2)
1062 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1063 goto leave;
1065 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1066 gcry_sexp_release (l2);
1067 if (!array[idx])
1069 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1070 goto leave;
1073 gcry_sexp_release (list);
1075 leave:
1076 if (rc)
1078 for (i=0; i<idx; i++)
1080 xfree (array[i]);
1081 array[i] = NULL;
1083 gcry_sexp_release (list);
1085 return rc;
1089 static int
1090 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
1092 int rc = 0;
1094 if (dek)
1096 sk->protect.algo = dek->algo;
1097 sk->protect.s2k = *s2k;
1098 rc = protect_secret_key (sk, dek);
1099 if (rc)
1100 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
1103 return rc;
1106 static void
1107 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
1109 (void)misc_key_info;
1110 (void)sec_root;
1111 #if 0 /* Not used anymore */
1112 size_t n;
1113 char *buf;
1115 if (misc_key_info)
1117 /* DSA: don't know whether it makes sense to have the factors, so for now
1118 we store them in the secret keyring (but they are not secret)
1119 p = 2 * q * f1 * f2 * ... * fn
1120 We store only f1 to f_n-1; fn can be calculated because p and q
1121 are known. */
1122 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
1123 buf = xmalloc (n+4);
1124 strcpy (buf, "#::");
1125 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
1126 if (n)
1128 n += 3;
1129 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
1131 xfree (buf);
1132 gcry_sexp_release (misc_key_info);
1134 #endif
1138 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1139 time to be put into the key structure. */
1140 static int
1141 gen_elg (int algo, unsigned int nbits,
1142 KBNODE pub_root, KBNODE sec_root, DEK *dek,
1143 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1144 u32 timestamp, u32 expireval, int is_subkey)
1146 int rc;
1147 PACKET *pkt;
1148 PKT_secret_key *sk;
1149 PKT_public_key *pk;
1150 gcry_sexp_t s_parms, s_key;
1151 gcry_sexp_t misc_key_info;
1153 assert( is_ELGAMAL(algo) );
1155 if (nbits < 512)
1157 nbits = 1024;
1158 log_info (_("keysize invalid; using %u bits\n"), nbits );
1161 if ((nbits % 32))
1163 nbits = ((nbits + 31) / 32) * 32;
1164 log_info (_("keysize rounded up to %u bits\n"), nbits );
1168 rc = gcry_sexp_build ( &s_parms, NULL,
1169 "(genkey(%s(nbits %d)))",
1170 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1171 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1172 (int)nbits);
1173 if (rc)
1174 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1176 rc = gcry_pk_genkey (&s_key, s_parms);
1177 gcry_sexp_release (s_parms);
1178 if (rc)
1180 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1181 return rc;
1184 sk = xmalloc_clear( sizeof *sk );
1185 pk = xmalloc_clear( sizeof *pk );
1186 sk->timestamp = pk->timestamp = timestamp;
1187 sk->version = pk->version = 4;
1188 if (expireval)
1190 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1192 sk->pubkey_algo = pk->pubkey_algo = algo;
1194 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
1195 if (rc)
1197 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1198 gcry_sexp_release (s_key);
1199 free_secret_key (sk);
1200 free_public_key (pk);
1201 return rc;
1203 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
1204 if (rc)
1206 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1207 gcry_sexp_release (s_key);
1208 free_secret_key (sk);
1209 free_public_key (pk);
1210 return rc;
1212 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1213 gcry_sexp_release (s_key);
1215 sk->is_protected = 0;
1216 sk->protect.algo = 0;
1218 sk->csum = checksum_mpi (sk->skey[3]);
1219 if (ret_sk) /* Return an unprotected version of the sk. */
1220 *ret_sk = copy_secret_key ( NULL, sk );
1222 rc = genhelp_protect (dek, s2k, sk);
1223 if (rc)
1225 free_public_key (pk);
1226 free_secret_key (sk);
1227 gcry_sexp_release (misc_key_info);
1228 return rc;
1231 pkt = xmalloc_clear (sizeof *pkt);
1232 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1233 pkt->pkt.public_key = pk;
1234 add_kbnode (pub_root, new_kbnode( pkt ));
1236 /* Don't know whether it makes sense to have access to the factors,
1237 so for now we store them in the secret keyring (but they are not
1238 secret). */
1239 pkt = xmalloc_clear (sizeof *pkt);
1240 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1241 pkt->pkt.secret_key = sk;
1242 add_kbnode (sec_root, new_kbnode( pkt ));
1244 genhelp_factors (misc_key_info, sec_root);
1246 return 0;
1250 /****************
1251 * Generate a DSA key
1253 static int
1254 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1255 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1256 u32 timestamp, u32 expireval, int is_subkey)
1258 int rc;
1259 PACKET *pkt;
1260 PKT_secret_key *sk;
1261 PKT_public_key *pk;
1262 gcry_sexp_t s_parms, s_key;
1263 gcry_sexp_t misc_key_info;
1264 unsigned int qbits;
1266 if ( nbits < 512 || (!opt.flags.dsa2 && nbits > 1024))
1268 nbits = 1024;
1269 log_info(_("keysize invalid; using %u bits\n"), nbits );
1271 else if ( nbits > 3072 )
1273 nbits = 3072;
1274 log_info(_("keysize invalid; using %u bits\n"), nbits );
1277 if( (nbits % 64) )
1279 nbits = ((nbits + 63) / 64) * 64;
1280 log_info(_("keysize rounded up to %u bits\n"), nbits );
1284 Figure out a q size based on the key size. FIPS 180-3 says:
1286 L = 1024, N = 160
1287 L = 2048, N = 224
1288 L = 2048, N = 256
1289 L = 3072, N = 256
1291 2048/256 is an odd pair since there is also a 2048/224 and
1292 3072/256. Matching sizes is not a very exact science.
1294 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1295 but less than 2048, and 160 for 1024 (DSA1).
1298 if (nbits > 2048)
1299 qbits = 256;
1300 else if ( nbits > 1024)
1301 qbits = 224;
1302 else
1303 qbits = 160;
1305 if (qbits != 160 )
1306 log_info (_("WARNING: some OpenPGP programs can't"
1307 " handle a DSA key with this digest size\n"));
1309 rc = gcry_sexp_build (&s_parms, NULL,
1310 "(genkey(dsa(nbits %d)(qbits %d)))",
1311 (int)nbits, (int)qbits);
1312 if (rc)
1313 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1315 rc = gcry_pk_genkey (&s_key, s_parms);
1316 gcry_sexp_release (s_parms);
1317 if (rc)
1319 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1320 return rc;
1323 sk = xmalloc_clear( sizeof *sk );
1324 pk = xmalloc_clear( sizeof *pk );
1325 sk->timestamp = pk->timestamp = timestamp;
1326 sk->version = pk->version = 4;
1327 if (expireval)
1328 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1329 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1331 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1332 if (rc)
1334 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1335 gcry_sexp_release (s_key);
1336 free_public_key(pk);
1337 free_secret_key(sk);
1338 return rc;
1340 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1341 if (rc)
1343 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1344 gcry_sexp_release (s_key);
1345 free_public_key(pk);
1346 free_secret_key(sk);
1347 return rc;
1349 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1350 gcry_sexp_release (s_key);
1352 sk->is_protected = 0;
1353 sk->protect.algo = 0;
1355 sk->csum = checksum_mpi ( sk->skey[4] );
1356 if( ret_sk ) /* return an unprotected version of the sk */
1357 *ret_sk = copy_secret_key( NULL, sk );
1359 rc = genhelp_protect (dek, s2k, sk);
1360 if (rc)
1362 free_public_key (pk);
1363 free_secret_key (sk);
1364 gcry_sexp_release (misc_key_info);
1365 return rc;
1368 pkt = xmalloc_clear(sizeof *pkt);
1369 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1370 pkt->pkt.public_key = pk;
1371 add_kbnode(pub_root, new_kbnode( pkt ));
1373 /* Don't know whether it makes sense to have the factors, so for now
1374 * we store them in the secret keyring (but they are not secret)
1375 * p = 2 * q * f1 * f2 * ... * fn
1376 * We store only f1 to f_n-1; fn can be calculated because p and q
1377 * are known.
1379 pkt = xmalloc_clear(sizeof *pkt);
1380 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1381 pkt->pkt.secret_key = sk;
1382 add_kbnode(sec_root, new_kbnode( pkt ));
1384 genhelp_factors (misc_key_info, sec_root);
1386 return 0;
1391 * Generate an RSA key.
1393 static int
1394 gen_rsa (int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1395 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1396 u32 timestamp, u32 expireval, int is_subkey)
1398 int rc;
1399 PACKET *pkt;
1400 PKT_secret_key *sk;
1401 PKT_public_key *pk;
1402 gcry_sexp_t s_parms, s_key;
1404 assert (is_RSA(algo));
1406 if (nbits < 1024)
1408 nbits = 1024;
1409 log_info (_("keysize invalid; using %u bits\n"), nbits );
1412 if ((nbits % 32))
1414 nbits = ((nbits + 31) / 32) * 32;
1415 log_info (_("keysize rounded up to %u bits\n"), nbits );
1418 rc = gcry_sexp_build (&s_parms, NULL,
1419 "(genkey(rsa(nbits %d)))",
1420 (int)nbits);
1421 if (rc)
1422 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1424 rc = gcry_pk_genkey (&s_key, s_parms);
1425 gcry_sexp_release (s_parms);
1426 if (rc)
1428 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1429 return rc;
1432 sk = xmalloc_clear( sizeof *sk );
1433 pk = xmalloc_clear( sizeof *pk );
1434 sk->timestamp = pk->timestamp = timestamp;
1435 sk->version = pk->version = 4;
1436 if (expireval)
1438 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1440 sk->pubkey_algo = pk->pubkey_algo = algo;
1442 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1443 if (rc)
1445 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1446 gcry_sexp_release (s_key);
1447 free_public_key(pk);
1448 free_secret_key(sk);
1449 return rc;
1451 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1452 if (rc)
1454 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1455 gcry_sexp_release (s_key);
1456 free_public_key(pk);
1457 free_secret_key(sk);
1458 return rc;
1460 gcry_sexp_release (s_key);
1462 sk->is_protected = 0;
1463 sk->protect.algo = 0;
1465 sk->csum = checksum_mpi (sk->skey[2] );
1466 sk->csum += checksum_mpi (sk->skey[3] );
1467 sk->csum += checksum_mpi (sk->skey[4] );
1468 sk->csum += checksum_mpi (sk->skey[5] );
1469 if( ret_sk ) /* return an unprotected version of the sk */
1470 *ret_sk = copy_secret_key( NULL, sk );
1472 rc = genhelp_protect (dek, s2k, sk);
1473 if (rc)
1475 free_public_key (pk);
1476 free_secret_key (sk);
1477 return rc;
1480 pkt = xmalloc_clear(sizeof *pkt);
1481 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1482 pkt->pkt.public_key = pk;
1483 add_kbnode(pub_root, new_kbnode( pkt ));
1485 pkt = xmalloc_clear(sizeof *pkt);
1486 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1487 pkt->pkt.secret_key = sk;
1488 add_kbnode(sec_root, new_kbnode( pkt ));
1490 return 0;
1494 /****************
1495 * check valid days:
1496 * return 0 on error or the multiplier
1498 static int
1499 check_valid_days( const char *s )
1501 if( !digitp(s) )
1502 return 0;
1503 for( s++; *s; s++)
1504 if( !digitp(s) )
1505 break;
1506 if( !*s )
1507 return 1;
1508 if( s[1] )
1509 return 0; /* e.g. "2323wc" */
1510 if( *s == 'd' || *s == 'D' )
1511 return 1;
1512 if( *s == 'w' || *s == 'W' )
1513 return 7;
1514 if( *s == 'm' || *s == 'M' )
1515 return 30;
1516 if( *s == 'y' || *s == 'Y' )
1517 return 365;
1518 return 0;
1522 static void
1523 print_key_flags(int flags)
1525 if(flags&PUBKEY_USAGE_SIG)
1526 tty_printf("%s ",_("Sign"));
1528 if(flags&PUBKEY_USAGE_CERT)
1529 tty_printf("%s ",_("Certify"));
1531 if(flags&PUBKEY_USAGE_ENC)
1532 tty_printf("%s ",_("Encrypt"));
1534 if(flags&PUBKEY_USAGE_AUTH)
1535 tty_printf("%s ",_("Authenticate"));
1539 /* Returns the key flags */
1540 static unsigned int
1541 ask_key_flags(int algo,int subkey)
1543 /* TRANSLATORS: Please use only plain ASCII characters for the
1544 translation. If this is not possible use single digits. The
1545 string needs to 8 bytes long. Here is a description of the
1546 functions:
1548 s = Toggle signing capability
1549 e = Toggle encryption capability
1550 a = Toggle authentication capability
1551 q = Finish
1553 const char *togglers=_("SsEeAaQq");
1554 char *answer=NULL;
1555 unsigned int current=0;
1556 unsigned int possible=openpgp_pk_algo_usage(algo);
1558 if ( strlen(togglers) != 7 )
1560 tty_printf ("NOTE: Bad translation at %s:%d. "
1561 "Please report.\n", __FILE__, __LINE__);
1562 togglers = "11223300";
1565 /* Only primary keys may certify. */
1566 if(subkey)
1567 possible&=~PUBKEY_USAGE_CERT;
1569 /* Preload the current set with the possible set, minus
1570 authentication, since nobody really uses auth yet. */
1571 current=possible&~PUBKEY_USAGE_AUTH;
1573 for(;;)
1575 tty_printf("\n");
1576 tty_printf(_("Possible actions for a %s key: "),
1577 gcry_pk_algo_name (algo));
1578 print_key_flags(possible);
1579 tty_printf("\n");
1580 tty_printf(_("Current allowed actions: "));
1581 print_key_flags(current);
1582 tty_printf("\n\n");
1584 if(possible&PUBKEY_USAGE_SIG)
1585 tty_printf(_(" (%c) Toggle the sign capability\n"),
1586 togglers[0]);
1587 if(possible&PUBKEY_USAGE_ENC)
1588 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1589 togglers[2]);
1590 if(possible&PUBKEY_USAGE_AUTH)
1591 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1592 togglers[4]);
1594 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1595 tty_printf("\n");
1597 xfree(answer);
1598 answer = cpr_get("keygen.flags",_("Your selection? "));
1599 cpr_kill_prompt();
1601 if(strlen(answer)>1)
1602 tty_printf(_("Invalid selection.\n"));
1603 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1604 break;
1605 else if((*answer==togglers[0] || *answer==togglers[1])
1606 && possible&PUBKEY_USAGE_SIG)
1608 if(current&PUBKEY_USAGE_SIG)
1609 current&=~PUBKEY_USAGE_SIG;
1610 else
1611 current|=PUBKEY_USAGE_SIG;
1613 else if((*answer==togglers[2] || *answer==togglers[3])
1614 && possible&PUBKEY_USAGE_ENC)
1616 if(current&PUBKEY_USAGE_ENC)
1617 current&=~PUBKEY_USAGE_ENC;
1618 else
1619 current|=PUBKEY_USAGE_ENC;
1621 else if((*answer==togglers[4] || *answer==togglers[5])
1622 && possible&PUBKEY_USAGE_AUTH)
1624 if(current&PUBKEY_USAGE_AUTH)
1625 current&=~PUBKEY_USAGE_AUTH;
1626 else
1627 current|=PUBKEY_USAGE_AUTH;
1629 else
1630 tty_printf(_("Invalid selection.\n"));
1633 xfree(answer);
1635 return current;
1639 /* Ask for an algorithm. The function returns the algorithm id to
1640 * create. If ADDMODE is false the function won't show an option to
1641 * create the primary and subkey combined and won't set R_USAGE
1642 * either. If a combined algorithm has been selected, the subkey
1643 * algorithm is stored at R_SUBKEY_ALGO. */
1644 static int
1645 ask_algo (int addmode, int *r_subkey_algo, unsigned int *r_usage)
1647 char *answer;
1648 int algo;
1649 int dummy_algo;
1651 if (!r_subkey_algo)
1652 r_subkey_algo = &dummy_algo;
1654 tty_printf (_("Please select what kind of key you want:\n"));
1656 if (!addmode)
1657 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1658 if (!addmode)
1659 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1661 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1662 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1664 if (addmode)
1666 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1667 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1669 if (opt.expert)
1671 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1672 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1675 for(;;)
1677 *r_usage = 0;
1678 *r_subkey_algo = 0;
1679 answer = cpr_get ("keygen.algo", _("Your selection? "));
1680 cpr_kill_prompt ();
1681 algo = *answer? atoi (answer) : 1;
1682 xfree(answer);
1683 if (algo == 1 && !addmode)
1685 algo = PUBKEY_ALGO_RSA;
1686 *r_subkey_algo = PUBKEY_ALGO_RSA;
1687 break;
1689 else if (algo == 2 && !addmode)
1691 algo = PUBKEY_ALGO_DSA;
1692 *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1693 break;
1695 else if (algo == 3)
1697 algo = PUBKEY_ALGO_DSA;
1698 *r_usage = PUBKEY_USAGE_SIG;
1699 break;
1701 else if (algo == 4)
1703 algo = PUBKEY_ALGO_RSA;
1704 *r_usage = PUBKEY_USAGE_SIG;
1705 break;
1707 else if (algo == 5 && addmode)
1709 algo = PUBKEY_ALGO_ELGAMAL_E;
1710 *r_usage = PUBKEY_USAGE_ENC;
1711 break;
1713 else if (algo == 6 && addmode)
1715 algo = PUBKEY_ALGO_RSA;
1716 *r_usage = PUBKEY_USAGE_ENC;
1717 break;
1719 else if (algo == 7 && opt.expert)
1721 algo = PUBKEY_ALGO_DSA;
1722 *r_usage = ask_key_flags (algo, addmode);
1723 break;
1725 else if (algo == 8 && opt.expert)
1727 algo = PUBKEY_ALGO_RSA;
1728 *r_usage = ask_key_flags (algo, addmode);
1729 break;
1731 else
1732 tty_printf (_("Invalid selection.\n"));
1735 return algo;
1739 /* Ask for the key size. ALGO is the algorithjm. If PRIMARY_KEYSIZE
1740 is not 0, the function asks for the size of the encryption
1741 subkey. */
1742 static unsigned
1743 ask_keysize (int algo, unsigned int primary_keysize)
1745 unsigned int nbits, min, def=2048, max=4096;
1746 int for_subkey = !!primary_keysize;
1747 int autocomp = 0;
1749 if(opt.expert)
1750 min=512;
1751 else
1752 min=1024;
1754 if (primary_keysize && !opt.expert)
1756 /* Deduce the subkey size from the primary key size. */
1757 if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
1758 nbits = 3072; /* For performance reasons we don't support more
1759 than 3072 bit DSA. However we won't see this
1760 case anyway because DSA can't be used as an
1761 encryption subkey ;-). */
1762 else
1763 nbits = primary_keysize;
1764 autocomp = 1;
1765 goto leave;
1768 switch(algo)
1770 case PUBKEY_ALGO_DSA:
1771 if(opt.flags.dsa2)
1773 def=2048;
1774 max=3072;
1776 else
1778 tty_printf(_("DSA keypair will have %u bits.\n"),1024);
1779 return 1024;
1781 break;
1783 case PUBKEY_ALGO_RSA:
1784 min=1024;
1785 break;
1788 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1789 gcry_pk_algo_name (algo), min, max);
1791 for(;;)
1793 char *prompt, *answer;
1795 if (for_subkey)
1796 prompt = xasprintf (_("What keysize do you want "
1797 "for the subkey? (%u) "), def);
1798 else
1799 prompt = xasprintf (_("What keysize do you want? (%u) "), def);
1800 answer = cpr_get ("keygen.size", prompt);
1801 cpr_kill_prompt ();
1802 nbits = *answer? atoi (answer): def;
1803 xfree(prompt);
1804 xfree(answer);
1806 if(nbits<min || nbits>max)
1807 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1808 gcry_pk_algo_name (algo), min, max);
1809 else
1810 break;
1813 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1815 leave:
1816 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
1818 nbits = ((nbits + 63) / 64) * 64;
1819 if (!autocomp)
1820 tty_printf(_("rounded up to %u bits\n"), nbits );
1822 else if( (nbits % 32) )
1824 nbits = ((nbits + 31) / 32) * 32;
1825 if (!autocomp)
1826 tty_printf(_("rounded up to %u bits\n"), nbits );
1829 return nbits;
1833 /****************
1834 * Parse an expire string and return its value in seconds.
1835 * Returns (u32)-1 on error.
1836 * This isn't perfect since scan_isodatestr returns unix time, and
1837 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1838 * Because of this, we only permit setting expirations up to 2106, but
1839 * OpenPGP could theoretically allow up to 2242. I think we'll all
1840 * just cope for the next few years until we get a 64-bit time_t or
1841 * similar.
1844 parse_expire_string( const char *string )
1846 int mult;
1847 u32 seconds;
1848 u32 abs_date = 0;
1849 u32 curtime = make_timestamp ();
1850 time_t tt;
1852 if (!*string)
1853 seconds = 0;
1854 else if (!strncmp (string, "seconds=", 8))
1855 seconds = atoi (string+8);
1856 else if ((abs_date = scan_isodatestr(string))
1857 && (abs_date+86400/2) > curtime)
1858 seconds = (abs_date+86400/2) - curtime;
1859 else if ((tt = isotime2epoch (string)) != (time_t)(-1))
1860 seconds = (u32)tt - curtime;
1861 else if ((mult = check_valid_days (string)))
1862 seconds = atoi (string) * 86400L * mult;
1863 else
1864 seconds = (u32)(-1);
1866 return seconds;
1869 /* Parsean Creation-Date string which is either "1986-04-26" or
1870 "19860426T042640". Returns 0 on error. */
1871 static u32
1872 parse_creation_string (const char *string)
1874 u32 seconds;
1876 if (!*string)
1877 seconds = 0;
1878 else if ( !strncmp (string, "seconds=", 8) )
1879 seconds = atoi (string+8);
1880 else if ( !(seconds = scan_isodatestr (string)))
1882 time_t tmp = isotime2epoch (string);
1883 seconds = (tmp == (time_t)(-1))? 0 : tmp;
1885 return seconds;
1889 /* object == 0 for a key, and 1 for a sig */
1891 ask_expire_interval(int object,const char *def_expire)
1893 u32 interval;
1894 char *answer;
1896 switch(object)
1898 case 0:
1899 if(def_expire)
1900 BUG();
1901 tty_printf(_("Please specify how long the key should be valid.\n"
1902 " 0 = key does not expire\n"
1903 " <n> = key expires in n days\n"
1904 " <n>w = key expires in n weeks\n"
1905 " <n>m = key expires in n months\n"
1906 " <n>y = key expires in n years\n"));
1907 break;
1909 case 1:
1910 if(!def_expire)
1911 BUG();
1912 tty_printf(_("Please specify how long the signature should be valid.\n"
1913 " 0 = signature does not expire\n"
1914 " <n> = signature expires in n days\n"
1915 " <n>w = signature expires in n weeks\n"
1916 " <n>m = signature expires in n months\n"
1917 " <n>y = signature expires in n years\n"));
1918 break;
1920 default:
1921 BUG();
1924 /* Note: The elgamal subkey for DSA has no expiration date because
1925 * it must be signed with the DSA key and this one has the expiration
1926 * date */
1928 answer = NULL;
1929 for(;;)
1931 u32 curtime=make_timestamp();
1933 xfree(answer);
1934 if(object==0)
1935 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1936 else
1938 char *prompt;
1940 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1941 /* This will actually end up larger than necessary because
1942 of the 2 bytes for '%s' */
1943 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
1944 sprintf(prompt,PROMPTSTRING,def_expire);
1945 #undef PROMPTSTRING
1947 answer = cpr_get("siggen.valid",prompt);
1948 xfree(prompt);
1950 if(*answer=='\0')
1951 answer=xstrdup(def_expire);
1953 cpr_kill_prompt();
1954 trim_spaces(answer);
1955 interval = parse_expire_string( answer );
1956 if( interval == (u32)-1 )
1958 tty_printf(_("invalid value\n"));
1959 continue;
1962 if( !interval )
1964 tty_printf((object==0)
1965 ? _("Key does not expire at all\n")
1966 : _("Signature does not expire at all\n"));
1968 else
1970 tty_printf(object==0
1971 ? _("Key expires at %s\n")
1972 : _("Signature expires at %s\n"),
1973 asctimestamp((ulong)(curtime + interval) ) );
1974 #if SIZEOF_TIME_T <= 4
1975 if ( (time_t)((ulong)(curtime+interval)) < 0 )
1976 tty_printf (_("Your system can't display dates beyond 2038.\n"
1977 "However, it will be correctly handled up to"
1978 " 2106.\n"));
1979 else
1980 #endif /*SIZEOF_TIME_T*/
1981 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
1983 tty_printf (_("invalid value\n"));
1984 continue;
1988 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1989 _("Is this correct? (y/N) ")) )
1990 break;
1993 xfree(answer);
1994 return interval;
1998 ask_expiredate()
2000 u32 x = ask_expire_interval(0,NULL);
2001 return x? make_timestamp() + x : 0;
2005 static char *
2006 ask_user_id( int mode )
2008 char *answer;
2009 char *aname, *acomment, *amail, *uid;
2011 if ( !mode )
2013 /* TRANSLATORS: This is the new string telling the user what
2014 gpg is now going to do (i.e. ask for the parts of the user
2015 ID). Note that if you do not tyranslated this string, a
2016 different string will be used used, which might still have
2017 a correct transaltion. */
2018 const char *s1 =
2019 N_("\n"
2020 "GnuPG needs to construct a user ID to identify your key.\n"
2021 "\n");
2022 const char *s2 = _(s1);
2024 if (!strcmp (s1, s2))
2026 /* There is no translation for the string thus we to use
2027 the old info text. gettext has no way to tell whether
2028 a translation is actually available, thus we need to
2029 to compare again. */
2030 /* TRANSLATORS: This string is in general not anymore used
2031 but you should keep your existing translation. In case
2032 the new string is not translated this old string will
2033 be used. */
2034 const char *s3 = N_("\n"
2035 "You need a user ID to identify your key; "
2036 "the software constructs the user ID\n"
2037 "from the Real Name, Comment and Email Address in this form:\n"
2038 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2039 const char *s4 = _(s3);
2040 if (strcmp (s3, s4))
2041 s2 = s3; /* A translation exists - use it. */
2043 tty_printf ("%s", s2) ;
2045 uid = aname = acomment = amail = NULL;
2046 for(;;) {
2047 char *p;
2048 int fail=0;
2050 if( !aname ) {
2051 for(;;) {
2052 xfree(aname);
2053 aname = cpr_get("keygen.name",_("Real name: "));
2054 trim_spaces(aname);
2055 cpr_kill_prompt();
2057 if( opt.allow_freeform_uid )
2058 break;
2060 if( strpbrk( aname, "<>" ) )
2061 tty_printf(_("Invalid character in name\n"));
2062 else if( digitp(aname) )
2063 tty_printf(_("Name may not start with a digit\n"));
2064 else if( strlen(aname) < 5 )
2065 tty_printf(_("Name must be at least 5 characters long\n"));
2066 else
2067 break;
2070 if( !amail ) {
2071 for(;;) {
2072 xfree(amail);
2073 amail = cpr_get("keygen.email",_("Email address: "));
2074 trim_spaces(amail);
2075 cpr_kill_prompt();
2076 if( !*amail || opt.allow_freeform_uid )
2077 break; /* no email address is okay */
2078 else if ( !is_valid_mailbox (amail) )
2079 tty_printf(_("Not a valid email address\n"));
2080 else
2081 break;
2084 if( !acomment ) {
2085 for(;;) {
2086 xfree(acomment);
2087 acomment = cpr_get("keygen.comment",_("Comment: "));
2088 trim_spaces(acomment);
2089 cpr_kill_prompt();
2090 if( !*acomment )
2091 break; /* no comment is okay */
2092 else if( strpbrk( acomment, "()" ) )
2093 tty_printf(_("Invalid character in comment\n"));
2094 else
2095 break;
2100 xfree(uid);
2101 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2102 p = stpcpy(p, aname );
2103 if( *acomment )
2104 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2105 if( *amail )
2106 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2108 /* Append a warning if the RNG is switched into fake mode. */
2109 if ( random_is_faked () )
2110 strcpy(p, " (insecure!)" );
2112 /* print a note in case that UTF8 mapping has to be done */
2113 for(p=uid; *p; p++ ) {
2114 if( *p & 0x80 ) {
2115 tty_printf(_("You are using the `%s' character set.\n"),
2116 get_native_charset() );
2117 break;
2121 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2122 /* fixme: add a warning if this user-id already exists */
2123 if( !*amail && !opt.allow_freeform_uid
2124 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2125 fail = 1;
2126 tty_printf(_("Please don't put the email address "
2127 "into the real name or the comment\n") );
2130 for(;;) {
2131 /* TRANSLATORS: These are the allowed answers in
2132 lower and uppercase. Below you will find the matching
2133 string which should be translated accordingly and the
2134 letter changed to match the one in the answer string.
2136 n = Change name
2137 c = Change comment
2138 e = Change email
2139 o = Okay (ready, continue)
2140 q = Quit
2142 const char *ansstr = _("NnCcEeOoQq");
2144 if( strlen(ansstr) != 10 )
2145 BUG();
2146 if( cpr_enabled() ) {
2147 answer = xstrdup(ansstr+6);
2148 answer[1] = 0;
2150 else {
2151 answer = cpr_get("keygen.userid.cmd", fail?
2152 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2153 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2154 cpr_kill_prompt();
2156 if( strlen(answer) > 1 )
2158 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2159 xfree(aname); aname = NULL;
2160 break;
2162 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2163 xfree(acomment); acomment = NULL;
2164 break;
2166 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2167 xfree(amail); amail = NULL;
2168 break;
2170 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2171 if( fail ) {
2172 tty_printf(_("Please correct the error first\n"));
2174 else {
2175 xfree(aname); aname = NULL;
2176 xfree(acomment); acomment = NULL;
2177 xfree(amail); amail = NULL;
2178 break;
2181 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2182 xfree(aname); aname = NULL;
2183 xfree(acomment); acomment = NULL;
2184 xfree(amail); amail = NULL;
2185 xfree(uid); uid = NULL;
2186 break;
2188 xfree(answer);
2190 xfree(answer);
2191 if( !amail && !acomment && !amail )
2192 break;
2193 xfree(uid); uid = NULL;
2195 if( uid ) {
2196 char *p = native_to_utf8( uid );
2197 xfree( uid );
2198 uid = p;
2200 return uid;
2204 /* MODE 0 - standard
2205 1 - Ask for passphrase of the card backup key. */
2206 static DEK *
2207 do_ask_passphrase (STRING2KEY **ret_s2k, int mode, int *r_canceled)
2209 DEK *dek = NULL;
2210 STRING2KEY *s2k;
2211 const char *errtext = NULL;
2212 const char *custdesc = NULL;
2214 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2216 if (mode == 1)
2217 custdesc = _("Please enter a passphrase to protect the off-card "
2218 "backup of the new encryption key.");
2220 s2k = xmalloc_secure( sizeof *s2k );
2221 for(;;) {
2222 s2k->mode = opt.s2k_mode;
2223 s2k->hash_algo = S2K_DIGEST_ALGO;
2224 dek = passphrase_to_dek_ext (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2225 errtext, custdesc, NULL, r_canceled);
2226 if (!dek && *r_canceled) {
2227 xfree(dek); dek = NULL;
2228 xfree(s2k); s2k = NULL;
2229 break;
2231 else if( !dek ) {
2232 errtext = N_("passphrase not correctly repeated; try again");
2233 tty_printf(_("%s.\n"), _(errtext));
2235 else if( !dek->keylen ) {
2236 xfree(dek); dek = NULL;
2237 xfree(s2k); s2k = NULL;
2238 tty_printf(_(
2239 "You don't want a passphrase - this is probably a *bad* idea!\n"
2240 "I will do it anyway. You can change your passphrase at any time,\n"
2241 "using this program with the option \"--edit-key\".\n\n"));
2242 break;
2244 else
2245 break; /* okay */
2247 *ret_s2k = s2k;
2248 return dek;
2252 /* Basic key generation. Here we divert to the actual generation
2253 routines based on the requested algorithm. */
2254 static int
2255 do_create (int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
2256 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk,
2257 u32 timestamp, u32 expiredate, int is_subkey )
2259 int rc=0;
2261 if( !opt.batch )
2262 tty_printf(_(
2263 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2264 "some other action (type on the keyboard, move the mouse, utilize the\n"
2265 "disks) during the prime generation; this gives the random number\n"
2266 "generator a better chance to gain enough entropy.\n") );
2268 if( algo == PUBKEY_ALGO_ELGAMAL_E )
2269 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2270 timestamp, expiredate, is_subkey);
2271 else if( algo == PUBKEY_ALGO_DSA )
2272 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk,
2273 timestamp, expiredate, is_subkey);
2274 else if( algo == PUBKEY_ALGO_RSA )
2275 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2276 timestamp, expiredate, is_subkey);
2277 else
2278 BUG();
2280 return rc;
2284 /****************
2285 * Generate a new user id packet, or return NULL if canceled
2287 PKT_user_id *
2288 generate_user_id()
2290 PKT_user_id *uid;
2291 char *p;
2292 size_t n;
2294 p = ask_user_id( 1 );
2295 if( !p )
2296 return NULL;
2297 n = strlen(p);
2298 uid = xmalloc_clear( sizeof *uid + n );
2299 uid->len = n;
2300 strcpy(uid->name, p);
2301 uid->ref = 1;
2302 return uid;
2306 static void
2307 release_parameter_list( struct para_data_s *r )
2309 struct para_data_s *r2;
2311 for( ; r ; r = r2 ) {
2312 r2 = r->next;
2313 if( r->key == pPASSPHRASE_DEK )
2314 xfree( r->u.dek );
2315 else if( r->key == pPASSPHRASE_S2K )
2316 xfree( r->u.s2k );
2318 xfree(r);
2322 static struct para_data_s *
2323 get_parameter( struct para_data_s *para, enum para_name key )
2325 struct para_data_s *r;
2327 for( r = para; r && r->key != key; r = r->next )
2329 return r;
2332 static const char *
2333 get_parameter_value( struct para_data_s *para, enum para_name key )
2335 struct para_data_s *r = get_parameter( para, key );
2336 return (r && *r->u.value)? r->u.value : NULL;
2339 static int
2340 get_parameter_algo( struct para_data_s *para, enum para_name key )
2342 int i;
2343 struct para_data_s *r = get_parameter( para, key );
2344 if( !r )
2345 return -1;
2346 if( digitp( r->u.value ) )
2347 i = atoi( r->u.value );
2348 else if ( !strcmp ( r->u.value, "ELG-E")
2349 || !strcmp ( r->u.value, "ELG") )
2350 i = GCRY_PK_ELG_E;
2351 else
2352 i = gcry_pk_map_name (r->u.value);
2353 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2354 i = 0; /* we don't want to allow generation of these algorithms */
2355 return i;
2359 * Parse the usage parameter and set the keyflags. Returns -1 on
2360 * error, 0 for no usage given or 1 for usage available.
2362 static int
2363 parse_parameter_usage (const char *fname,
2364 struct para_data_s *para, enum para_name key)
2366 struct para_data_s *r = get_parameter( para, key );
2367 char *p, *pn;
2368 unsigned int use;
2370 if( !r )
2371 return 0; /* none (this is an optional parameter)*/
2373 use = 0;
2374 pn = r->u.value;
2375 while ( (p = strsep (&pn, " \t,")) ) {
2376 if ( !*p)
2378 else if ( !ascii_strcasecmp (p, "sign") )
2379 use |= PUBKEY_USAGE_SIG;
2380 else if ( !ascii_strcasecmp (p, "encrypt") )
2381 use |= PUBKEY_USAGE_ENC;
2382 else if ( !ascii_strcasecmp (p, "auth") )
2383 use |= PUBKEY_USAGE_AUTH;
2384 else {
2385 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2386 return -1; /* error */
2389 r->u.usage = use;
2390 return 1;
2393 static int
2394 parse_revocation_key (const char *fname,
2395 struct para_data_s *para, enum para_name key)
2397 struct para_data_s *r = get_parameter( para, key );
2398 struct revocation_key revkey;
2399 char *pn;
2400 int i;
2402 if( !r )
2403 return 0; /* none (this is an optional parameter) */
2405 pn = r->u.value;
2407 revkey.class=0x80;
2408 revkey.algid=atoi(pn);
2409 if(!revkey.algid)
2410 goto fail;
2412 /* Skip to the fpr */
2413 while(*pn && *pn!=':')
2414 pn++;
2416 if(*pn!=':')
2417 goto fail;
2419 pn++;
2421 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2423 int c=hextobyte(pn);
2424 if(c==-1)
2425 goto fail;
2427 revkey.fpr[i]=c;
2430 /* skip to the tag */
2431 while(*pn && *pn!='s' && *pn!='S')
2432 pn++;
2434 if(ascii_strcasecmp(pn,"sensitive")==0)
2435 revkey.class|=0x40;
2437 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2439 return 0;
2441 fail:
2442 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2443 return -1; /* error */
2447 static u32
2448 get_parameter_u32( struct para_data_s *para, enum para_name key )
2450 struct para_data_s *r = get_parameter( para, key );
2452 if( !r )
2453 return 0;
2454 if( r->key == pKEYCREATIONDATE )
2455 return r->u.creation;
2456 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2457 return r->u.expire;
2458 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2459 return r->u.usage;
2461 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2464 static unsigned int
2465 get_parameter_uint( struct para_data_s *para, enum para_name key )
2467 return get_parameter_u32( para, key );
2470 static DEK *
2471 get_parameter_dek( struct para_data_s *para, enum para_name key )
2473 struct para_data_s *r = get_parameter( para, key );
2474 return r? r->u.dek : NULL;
2477 static STRING2KEY *
2478 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2480 struct para_data_s *r = get_parameter( para, key );
2481 return r? r->u.s2k : NULL;
2484 static struct revocation_key *
2485 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2487 struct para_data_s *r = get_parameter( para, key );
2488 return r? &r->u.revkey : NULL;
2491 static int
2492 proc_parameter_file( struct para_data_s *para, const char *fname,
2493 struct output_control_s *outctrl, int card )
2495 struct para_data_s *r;
2496 const char *s1, *s2, *s3;
2497 size_t n;
2498 char *p;
2499 int have_user_id=0,err,algo;
2501 /* Check that we have all required parameters. */
2502 r = get_parameter( para, pKEYTYPE );
2503 if(r)
2505 algo=get_parameter_algo(para,pKEYTYPE);
2506 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2508 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2509 return -1;
2512 else
2514 log_error ("%s: no Key-Type specified\n",fname);
2515 return -1;
2518 err = parse_parameter_usage (fname, para, pKEYUSAGE);
2519 if (!err)
2521 /* Default to algo capabilities if key-usage is not provided */
2522 r = xmalloc_clear(sizeof(*r));
2523 r->key = pKEYUSAGE;
2524 r->u.usage = openpgp_pk_algo_usage(algo);
2525 r->next = para;
2526 para = r;
2528 else if (err == -1)
2529 return -1;
2530 else
2532 r = get_parameter (para, pKEYUSAGE);
2533 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2535 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2536 fname, r->lnr, algo);
2537 return -1;
2541 r = get_parameter( para, pSUBKEYTYPE );
2542 if(r)
2544 algo = get_parameter_algo (para, pSUBKEYTYPE);
2545 if (openpgp_pk_test_algo (algo))
2547 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2548 return -1;
2551 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2552 if (!err)
2554 /* Default to algo capabilities if subkey-usage is not
2555 provided */
2556 r = xmalloc_clear (sizeof(*r));
2557 r->key = pSUBKEYUSAGE;
2558 r->u.usage = openpgp_pk_algo_usage (algo);
2559 r->next = para;
2560 para = r;
2562 else if (err == -1)
2563 return -1;
2564 else
2566 r = get_parameter (para, pSUBKEYUSAGE);
2567 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2569 log_error ("%s:%d: specified Subkey-Usage not allowed"
2570 " for algo %d\n", fname, r->lnr, algo);
2571 return -1;
2577 if( get_parameter_value( para, pUSERID ) )
2578 have_user_id=1;
2579 else
2581 /* create the formatted user ID */
2582 s1 = get_parameter_value( para, pNAMEREAL );
2583 s2 = get_parameter_value( para, pNAMECOMMENT );
2584 s3 = get_parameter_value( para, pNAMEEMAIL );
2585 if( s1 || s2 || s3 )
2587 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2588 r = xmalloc_clear( sizeof *r + n + 20 );
2589 r->key = pUSERID;
2590 p = r->u.value;
2591 if( s1 )
2592 p = stpcpy(p, s1 );
2593 if( s2 )
2594 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2595 if( s3 )
2596 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2597 r->next = para;
2598 para = r;
2599 have_user_id=1;
2603 if(!have_user_id)
2605 log_error("%s: no User-ID specified\n",fname);
2606 return -1;
2609 /* Set preferences, if any. */
2610 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2612 /* Set keyserver, if any. */
2613 s1=get_parameter_value( para, pKEYSERVER );
2614 if(s1)
2616 struct keyserver_spec *spec;
2618 spec=parse_keyserver_uri(s1,1,NULL,0);
2619 if(spec)
2621 free_keyserver_spec(spec);
2622 opt.def_keyserver_url=s1;
2624 else
2626 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2627 return -1;
2631 /* Set revoker, if any. */
2632 if (parse_revocation_key (fname, para, pREVOKER))
2633 return -1;
2635 /* Make DEK and S2K from the Passphrase. */
2636 if (outctrl->ask_passphrase)
2638 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2639 feature is required so that GUIs are able to do a key
2640 creation but have gpg-agent ask for the passphrase. */
2641 int canceled = 0;
2642 STRING2KEY *s2k;
2643 DEK *dek;
2645 dek = do_ask_passphrase (&s2k, 0, &canceled);
2646 if (dek)
2648 r = xmalloc_clear( sizeof *r );
2649 r->key = pPASSPHRASE_DEK;
2650 r->u.dek = dek;
2651 r->next = para;
2652 para = r;
2653 r = xmalloc_clear( sizeof *r );
2654 r->key = pPASSPHRASE_S2K;
2655 r->u.s2k = s2k;
2656 r->next = para;
2657 para = r;
2660 if (canceled)
2662 log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
2663 return -1;
2666 else
2668 r = get_parameter( para, pPASSPHRASE );
2669 if ( r && *r->u.value )
2671 /* We have a plain text passphrase - create a DEK from it.
2672 * It is a little bit ridiculous to keep it in secure memory
2673 * but because we do this always, why not here. */
2674 STRING2KEY *s2k;
2675 DEK *dek;
2677 s2k = xmalloc_secure ( sizeof *s2k );
2678 s2k->mode = opt.s2k_mode;
2679 s2k->hash_algo = S2K_DIGEST_ALGO;
2680 set_next_passphrase ( r->u.value );
2681 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2682 NULL, NULL);
2683 set_next_passphrase (NULL );
2684 assert (dek);
2685 memset (r->u.value, 0, strlen(r->u.value));
2687 r = xmalloc_clear (sizeof *r);
2688 r->key = pPASSPHRASE_S2K;
2689 r->u.s2k = s2k;
2690 r->next = para;
2691 para = r;
2692 r = xmalloc_clear (sizeof *r);
2693 r->key = pPASSPHRASE_DEK;
2694 r->u.dek = dek;
2695 r->next = para;
2696 para = r;
2700 /* Make KEYCREATIONDATE from Creation-Date. */
2701 r = get_parameter (para, pCREATIONDATE);
2702 if (r && *r->u.value)
2704 u32 seconds;
2706 seconds = parse_creation_string (r->u.value);
2707 if (!seconds)
2709 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2710 return -1;
2712 r->u.creation = seconds;
2713 r->key = pKEYCREATIONDATE; /* Change that entry. */
2716 /* Make KEYEXPIRE from Expire-Date. */
2717 r = get_parameter( para, pEXPIREDATE );
2718 if( r && *r->u.value )
2720 u32 seconds;
2722 seconds = parse_expire_string( r->u.value );
2723 if( seconds == (u32)-1 )
2725 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2726 return -1;
2728 r->u.expire = seconds;
2729 r->key = pKEYEXPIRE; /* change hat entry */
2730 /* also set it for the subkey */
2731 r = xmalloc_clear( sizeof *r + 20 );
2732 r->key = pSUBKEYEXPIRE;
2733 r->u.expire = seconds;
2734 r->next = para;
2735 para = r;
2738 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2739 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2740 return -1;
2743 do_generate_keypair( para, outctrl, card );
2744 return 0;
2748 /****************
2749 * Kludge to allow non interactive key generation controlled
2750 * by a parameter file.
2751 * Note, that string parameters are expected to be in UTF-8
2753 static void
2754 read_parameter_file( const char *fname )
2756 static struct { const char *name;
2757 enum para_name key;
2758 } keywords[] = {
2759 { "Key-Type", pKEYTYPE},
2760 { "Key-Length", pKEYLENGTH },
2761 { "Key-Usage", pKEYUSAGE },
2762 { "Subkey-Type", pSUBKEYTYPE },
2763 { "Subkey-Length", pSUBKEYLENGTH },
2764 { "Subkey-Usage", pSUBKEYUSAGE },
2765 { "Name-Real", pNAMEREAL },
2766 { "Name-Email", pNAMEEMAIL },
2767 { "Name-Comment", pNAMECOMMENT },
2768 { "Expire-Date", pEXPIREDATE },
2769 { "Creation-Date", pCREATIONDATE },
2770 { "Passphrase", pPASSPHRASE },
2771 { "Preferences", pPREFERENCES },
2772 { "Revoker", pREVOKER },
2773 { "Handle", pHANDLE },
2774 { "Keyserver", pKEYSERVER },
2775 { NULL, 0 }
2777 IOBUF fp;
2778 byte *line;
2779 unsigned int maxlen, nline;
2780 char *p;
2781 int lnr;
2782 const char *err = NULL;
2783 struct para_data_s *para, *r;
2784 int i;
2785 struct output_control_s outctrl;
2787 memset( &outctrl, 0, sizeof( outctrl ) );
2788 outctrl.pub.afx = new_armor_context ();
2789 outctrl.sec.afx = new_armor_context ();
2791 if( !fname || !*fname)
2792 fname = "-";
2794 fp = iobuf_open (fname);
2795 if (fp && is_secured_file (iobuf_get_fd (fp)))
2797 iobuf_close (fp);
2798 fp = NULL;
2799 errno = EPERM;
2801 if (!fp) {
2802 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2803 return;
2805 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2807 lnr = 0;
2808 err = NULL;
2809 para = NULL;
2810 maxlen = 1024;
2811 line = NULL;
2812 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2813 char *keyword, *value;
2815 lnr++;
2816 if( !maxlen ) {
2817 err = "line too long";
2818 break;
2820 for( p = line; isspace(*(byte*)p); p++ )
2822 if( !*p || *p == '#' )
2823 continue;
2824 keyword = p;
2825 if( *keyword == '%' ) {
2826 for( ; !isspace(*(byte*)p); p++ )
2828 if( *p )
2829 *p++ = 0;
2830 for( ; isspace(*(byte*)p); p++ )
2832 value = p;
2833 trim_trailing_ws( value, strlen(value) );
2834 if( !ascii_strcasecmp( keyword, "%echo" ) )
2835 log_info("%s\n", value );
2836 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2837 outctrl.dryrun = 1;
2838 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
2839 outctrl.ask_passphrase = 1;
2840 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
2841 outctrl.ask_passphrase = 0;
2842 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2843 outctrl.lnr = lnr;
2844 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2845 print_status_key_not_created
2846 (get_parameter_value (para, pHANDLE));
2847 release_parameter_list( para );
2848 para = NULL;
2850 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2851 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2852 ; /* still the same file - ignore it */
2853 else {
2854 xfree( outctrl.pub.newfname );
2855 outctrl.pub.newfname = xstrdup( value );
2856 outctrl.use_files = 1;
2859 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2860 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2861 ; /* still the same file - ignore it */
2862 else {
2863 xfree( outctrl.sec.newfname );
2864 outctrl.sec.newfname = xstrdup( value );
2865 outctrl.use_files = 1;
2868 else
2869 log_info("skipping control `%s' (%s)\n", keyword, value );
2872 continue;
2876 if( !(p = strchr( p, ':' )) || p == keyword ) {
2877 err = "missing colon";
2878 break;
2880 if( *p )
2881 *p++ = 0;
2882 for( ; isspace(*(byte*)p); p++ )
2884 if( !*p ) {
2885 err = "missing argument";
2886 break;
2888 value = p;
2889 trim_trailing_ws( value, strlen(value) );
2891 for(i=0; keywords[i].name; i++ ) {
2892 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2893 break;
2895 if( !keywords[i].name ) {
2896 err = "unknown keyword";
2897 break;
2899 if( keywords[i].key != pKEYTYPE && !para ) {
2900 err = "parameter block does not start with \"Key-Type\"";
2901 break;
2904 if( keywords[i].key == pKEYTYPE && para ) {
2905 outctrl.lnr = lnr;
2906 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2907 print_status_key_not_created
2908 (get_parameter_value (para, pHANDLE));
2909 release_parameter_list( para );
2910 para = NULL;
2912 else {
2913 for( r = para; r; r = r->next ) {
2914 if( r->key == keywords[i].key )
2915 break;
2917 if( r ) {
2918 err = "duplicate keyword";
2919 break;
2922 r = xmalloc_clear( sizeof *r + strlen( value ) );
2923 r->lnr = lnr;
2924 r->key = keywords[i].key;
2925 strcpy( r->u.value, value );
2926 r->next = para;
2927 para = r;
2929 if( err )
2930 log_error("%s:%d: %s\n", fname, lnr, err );
2931 else if( iobuf_error (fp) ) {
2932 log_error("%s:%d: read error\n", fname, lnr);
2934 else if( para ) {
2935 outctrl.lnr = lnr;
2936 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2937 print_status_key_not_created (get_parameter_value (para, pHANDLE));
2940 if( outctrl.use_files ) { /* close open streams */
2941 iobuf_close( outctrl.pub.stream );
2942 iobuf_close( outctrl.sec.stream );
2944 /* Must invalidate that ugly cache to actually close it. */
2945 if (outctrl.pub.fname)
2946 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
2947 if (outctrl.sec.fname)
2948 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
2950 xfree( outctrl.pub.fname );
2951 xfree( outctrl.pub.newfname );
2952 xfree( outctrl.sec.fname );
2953 xfree( outctrl.sec.newfname );
2956 release_parameter_list( para );
2957 iobuf_close (fp);
2958 release_armor_context (outctrl.pub.afx);
2959 release_armor_context (outctrl.sec.afx);
2964 * Generate a keypair (fname is only used in batch mode) If
2965 * CARD_SERIALNO is not NULL the function will create the keys on an
2966 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2967 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2968 * generate in software, imported to the card and a backup file
2969 * written to directory given by this argument .
2971 void
2972 generate_keypair (const char *fname, const char *card_serialno,
2973 const char *backup_encryption_dir)
2975 unsigned int nbits;
2976 char *uid = NULL;
2977 DEK *dek;
2978 STRING2KEY *s2k;
2979 int algo;
2980 unsigned int use;
2981 int both = 0;
2982 u32 expire;
2983 struct para_data_s *para = NULL;
2984 struct para_data_s *r;
2985 struct output_control_s outctrl;
2986 int canceled;
2988 memset( &outctrl, 0, sizeof( outctrl ) );
2990 if (opt.batch && card_serialno)
2992 /* We don't yet support unattended key generation. */
2993 log_error (_("can't do this in batch mode\n"));
2994 return;
2997 if (opt.batch)
2999 read_parameter_file( fname );
3000 return;
3003 if (card_serialno)
3005 #ifdef ENABLE_CARD_SUPPORT
3006 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
3007 r->key = pSERIALNO;
3008 strcpy( r->u.value, card_serialno);
3009 r->next = para;
3010 para = r;
3012 algo = PUBKEY_ALGO_RSA;
3014 r = xcalloc (1, sizeof *r + 20 );
3015 r->key = pKEYTYPE;
3016 sprintf( r->u.value, "%d", algo );
3017 r->next = para;
3018 para = r;
3019 r = xcalloc (1, sizeof *r + 20 );
3020 r->key = pKEYUSAGE;
3021 strcpy (r->u.value, "sign");
3022 r->next = para;
3023 para = r;
3025 r = xcalloc (1, sizeof *r + 20 );
3026 r->key = pSUBKEYTYPE;
3027 sprintf( r->u.value, "%d", algo );
3028 r->next = para;
3029 para = r;
3030 r = xcalloc (1, sizeof *r + 20 );
3031 r->key = pSUBKEYUSAGE;
3032 strcpy (r->u.value, "encrypt");
3033 r->next = para;
3034 para = r;
3036 r = xcalloc (1, sizeof *r + 20 );
3037 r->key = pAUTHKEYTYPE;
3038 sprintf( r->u.value, "%d", algo );
3039 r->next = para;
3040 para = r;
3042 if (backup_encryption_dir)
3044 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
3045 r->key = pBACKUPENCDIR;
3046 strcpy (r->u.value, backup_encryption_dir);
3047 r->next = para;
3048 para = r;
3050 #endif /*ENABLE_CARD_SUPPORT*/
3052 else
3054 int subkey_algo;
3056 algo = ask_algo (0, &subkey_algo, &use);
3057 if (subkey_algo)
3059 /* Create primary and subkey at once. */
3060 both = 1;
3061 r = xmalloc_clear( sizeof *r + 20 );
3062 r->key = pKEYTYPE;
3063 sprintf( r->u.value, "%d", algo );
3064 r->next = para;
3065 para = r;
3066 nbits = ask_keysize (algo, 0);
3067 r = xmalloc_clear( sizeof *r + 20 );
3068 r->key = pKEYLENGTH;
3069 sprintf( r->u.value, "%u", nbits);
3070 r->next = para;
3071 para = r;
3072 r = xmalloc_clear( sizeof *r + 20 );
3073 r->key = pKEYUSAGE;
3074 strcpy( r->u.value, "sign" );
3075 r->next = para;
3076 para = r;
3078 r = xmalloc_clear( sizeof *r + 20 );
3079 r->key = pSUBKEYTYPE;
3080 sprintf( r->u.value, "%d", subkey_algo);
3081 r->next = para;
3082 para = r;
3083 r = xmalloc_clear( sizeof *r + 20 );
3084 r->key = pSUBKEYUSAGE;
3085 strcpy( r->u.value, "encrypt" );
3086 r->next = para;
3087 para = r;
3089 else
3091 r = xmalloc_clear( sizeof *r + 20 );
3092 r->key = pKEYTYPE;
3093 sprintf( r->u.value, "%d", algo );
3094 r->next = para;
3095 para = r;
3097 if (use)
3099 r = xmalloc_clear( sizeof *r + 25 );
3100 r->key = pKEYUSAGE;
3101 sprintf( r->u.value, "%s%s%s",
3102 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3103 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3104 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3105 r->next = para;
3106 para = r;
3108 nbits = 0;
3111 nbits = ask_keysize (algo, nbits);
3112 r = xmalloc_clear( sizeof *r + 20 );
3113 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3114 sprintf( r->u.value, "%u", nbits);
3115 r->next = para;
3116 para = r;
3119 expire = ask_expire_interval(0,NULL);
3120 r = xmalloc_clear( sizeof *r + 20 );
3121 r->key = pKEYEXPIRE;
3122 r->u.expire = expire;
3123 r->next = para;
3124 para = r;
3125 r = xmalloc_clear( sizeof *r + 20 );
3126 r->key = pSUBKEYEXPIRE;
3127 r->u.expire = expire;
3128 r->next = para;
3129 para = r;
3131 uid = ask_user_id(0);
3132 if( !uid )
3134 log_error(_("Key generation canceled.\n"));
3135 release_parameter_list( para );
3136 return;
3138 r = xmalloc_clear( sizeof *r + strlen(uid) );
3139 r->key = pUSERID;
3140 strcpy( r->u.value, uid );
3141 r->next = para;
3142 para = r;
3144 canceled = 0;
3145 dek = card_serialno? NULL : do_ask_passphrase (&s2k, 0, &canceled);
3146 if( dek )
3148 r = xmalloc_clear( sizeof *r );
3149 r->key = pPASSPHRASE_DEK;
3150 r->u.dek = dek;
3151 r->next = para;
3152 para = r;
3153 r = xmalloc_clear( sizeof *r );
3154 r->key = pPASSPHRASE_S2K;
3155 r->u.s2k = s2k;
3156 r->next = para;
3157 para = r;
3160 if (canceled)
3161 log_error (_("Key generation canceled.\n"));
3162 else
3163 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3164 release_parameter_list( para );
3168 #ifdef ENABLE_CARD_SUPPORT
3169 /* Generate a raw key and return it as a secret key packet. The
3170 function will ask for the passphrase and return a protected as well
3171 as an unprotected copy of a new secret key packet. 0 is returned
3172 on success and the caller must then free the returned values. */
3173 static int
3174 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3175 PKT_secret_key **r_sk_unprotected,
3176 PKT_secret_key **r_sk_protected)
3178 int rc;
3179 DEK *dek = NULL;
3180 STRING2KEY *s2k = NULL;
3181 PKT_secret_key *sk = NULL;
3182 int i;
3183 size_t nskey, npkey;
3184 gcry_sexp_t s_parms, s_key;
3185 int canceled;
3187 npkey = pubkey_get_npkey (algo);
3188 nskey = pubkey_get_nskey (algo);
3189 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3191 if (nbits < 512)
3193 nbits = 512;
3194 log_info (_("keysize invalid; using %u bits\n"), nbits );
3197 if ((nbits % 32))
3199 nbits = ((nbits + 31) / 32) * 32;
3200 log_info(_("keysize rounded up to %u bits\n"), nbits );
3203 dek = do_ask_passphrase (&s2k, 1, &canceled);
3204 if (canceled)
3206 rc = gpg_error (GPG_ERR_CANCELED);
3207 goto leave;
3210 sk = xmalloc_clear (sizeof *sk);
3211 sk->timestamp = created_at;
3212 sk->version = 4;
3213 sk->pubkey_algo = algo;
3215 if ( !is_RSA (algo) )
3217 log_error ("only RSA is supported for offline generated keys\n");
3218 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3219 goto leave;
3221 rc = gcry_sexp_build (&s_parms, NULL,
3222 "(genkey(rsa(nbits %d)))",
3223 (int)nbits);
3224 if (rc)
3225 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3226 rc = gcry_pk_genkey (&s_key, s_parms);
3227 gcry_sexp_release (s_parms);
3228 if (rc)
3230 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3231 goto leave;
3233 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3234 gcry_sexp_release (s_key);
3235 if (rc)
3237 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3238 goto leave;
3241 for (i=npkey; i < nskey; i++)
3242 sk->csum += checksum_mpi (sk->skey[i]);
3244 if (r_sk_unprotected)
3245 *r_sk_unprotected = copy_secret_key (NULL, sk);
3247 rc = genhelp_protect (dek, s2k, sk);
3248 if (rc)
3249 goto leave;
3251 if (r_sk_protected)
3253 *r_sk_protected = sk;
3254 sk = NULL;
3257 leave:
3258 if (sk)
3259 free_secret_key (sk);
3260 xfree (dek);
3261 xfree (s2k);
3262 return rc;
3264 #endif /* ENABLE_CARD_SUPPORT */
3266 /* Create and delete a dummy packet to start off a list of kbnodes. */
3267 static void
3268 start_tree(KBNODE *tree)
3270 PACKET *pkt;
3272 pkt=xmalloc_clear(sizeof(*pkt));
3273 pkt->pkttype=PKT_NONE;
3274 *tree=new_kbnode(pkt);
3275 delete_kbnode(*tree);
3279 static void
3280 do_generate_keypair (struct para_data_s *para,
3281 struct output_control_s *outctrl, int card)
3283 KBNODE pub_root = NULL;
3284 KBNODE sec_root = NULL;
3285 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3286 const char *s;
3287 struct revocation_key *revkey;
3288 int rc;
3289 int did_sub = 0;
3290 u32 timestamp;
3292 if( outctrl->dryrun )
3294 log_info("dry-run mode - key generation skipped\n");
3295 return;
3298 if ( outctrl->use_files )
3300 if ( outctrl->pub.newfname )
3302 iobuf_close(outctrl->pub.stream);
3303 outctrl->pub.stream = NULL;
3304 if (outctrl->pub.fname)
3305 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3306 xfree( outctrl->pub.fname );
3307 outctrl->pub.fname = outctrl->pub.newfname;
3308 outctrl->pub.newfname = NULL;
3310 if (is_secured_filename (outctrl->pub.fname) )
3312 outctrl->pub.stream = NULL;
3313 errno = EPERM;
3315 else
3316 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3317 if (!outctrl->pub.stream)
3319 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3320 strerror(errno) );
3321 return;
3323 if (opt.armor)
3325 outctrl->pub.afx->what = 1;
3326 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3329 if (outctrl->sec.newfname)
3331 mode_t oldmask;
3333 iobuf_close(outctrl->sec.stream);
3334 outctrl->sec.stream = NULL;
3335 if (outctrl->sec.fname)
3336 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3337 xfree( outctrl->sec.fname );
3338 outctrl->sec.fname = outctrl->sec.newfname;
3339 outctrl->sec.newfname = NULL;
3341 oldmask = umask (077);
3342 if (is_secured_filename (outctrl->sec.fname) )
3344 outctrl->sec.stream = NULL;
3345 errno = EPERM;
3347 else
3348 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3349 umask (oldmask);
3350 if (!outctrl->sec.stream)
3352 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3353 strerror(errno) );
3354 return;
3356 if (opt.armor)
3358 outctrl->sec.afx->what = 5;
3359 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3362 assert( outctrl->pub.stream );
3363 assert( outctrl->sec.stream );
3364 if (opt.verbose)
3366 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3367 if (card)
3368 log_info (_("writing secret key stub to `%s'\n"),
3369 outctrl->sec.fname);
3370 else
3371 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3376 /* We create the packets as a tree of kbnodes. Because the
3377 structure we create is known in advance we simply generate a
3378 linked list. The first packet is a dummy packet which we flag as
3379 deleted. The very first packet must always be a KEY packet. */
3381 start_tree (&pub_root);
3382 start_tree (&sec_root);
3384 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3385 if (!timestamp)
3386 timestamp = make_timestamp ();
3388 if (!card)
3390 rc = do_create (get_parameter_algo( para, pKEYTYPE ),
3391 get_parameter_uint( para, pKEYLENGTH ),
3392 pub_root, sec_root,
3393 get_parameter_dek( para, pPASSPHRASE_DEK ),
3394 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3395 &pri_sk,
3396 timestamp,
3397 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3399 else
3401 /* Note, that depending on the backend, the card key generation
3402 may update TIMESTAMP. */
3403 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3404 &timestamp,
3405 get_parameter_u32 (para, pKEYEXPIRE), para);
3406 if (!rc)
3408 pri_sk = sec_root->next->pkt->pkt.secret_key;
3409 assert (pri_sk);
3413 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3415 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3416 if (!rc)
3417 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3420 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3422 write_uid (pub_root, s );
3423 write_uid (sec_root, s );
3425 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3426 get_parameter_uint (para, pKEYUSAGE), timestamp);
3429 /* Write the auth key to the card before the encryption key. This
3430 is a partial workaround for a PGP bug (as of this writing, all
3431 versions including 8.1), that causes it to try and encrypt to
3432 the most recent subkey regardless of whether that subkey is
3433 actually an encryption type. In this case, the auth key is an
3434 RSA key so it succeeds. */
3436 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3438 /* Note, that depending on the backend, the card key generation
3439 may update TIMESTAMP. */
3440 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3441 &timestamp,
3442 get_parameter_u32 (para, pKEYEXPIRE), para);
3444 if (!rc)
3445 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3446 PUBKEY_USAGE_AUTH, timestamp);
3447 if (!rc)
3448 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3449 PUBKEY_USAGE_AUTH, timestamp);
3452 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3454 if (!card)
3456 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
3457 get_parameter_uint( para, pSUBKEYLENGTH ),
3458 pub_root, sec_root,
3459 get_parameter_dek( para, pPASSPHRASE_DEK ),
3460 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3461 &sub_sk,
3462 timestamp,
3463 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3465 else
3467 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3469 /* A backup of the encryption key has been requested.
3470 Generate the key in software and import it then to
3471 the card. Write a backup file. */
3472 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3473 pub_root, sec_root,
3474 timestamp,
3475 get_parameter_u32 (para,
3476 pKEYEXPIRE),
3477 para, s);
3479 else
3481 /* Note, that depending on the backend, the card key
3482 generation may update TIMESTAMP. */
3483 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3484 NULL,
3485 &timestamp,
3486 get_parameter_u32 (para, pKEYEXPIRE), para);
3490 if( !rc )
3491 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3492 get_parameter_uint (para, pSUBKEYUSAGE),
3493 timestamp);
3494 if( !rc )
3495 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3496 get_parameter_uint (para, pSUBKEYUSAGE),
3497 timestamp);
3498 did_sub = 1;
3501 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3503 rc = write_keyblock( outctrl->pub.stream, pub_root );
3504 if (rc)
3505 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3506 if (!rc)
3508 rc = write_keyblock( outctrl->sec.stream, sec_root );
3509 if(rc)
3510 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3513 else if (!rc) /* Write to the standard keyrings. */
3515 KEYDB_HANDLE pub_hd = keydb_new (0);
3516 KEYDB_HANDLE sec_hd = keydb_new (1);
3518 rc = keydb_locate_writable (pub_hd, NULL);
3519 if (rc)
3520 log_error (_("no writable public keyring found: %s\n"),
3521 g10_errstr (rc));
3523 if (!rc)
3525 rc = keydb_locate_writable (sec_hd, NULL);
3526 if (rc)
3527 log_error (_("no writable secret keyring found: %s\n"),
3528 g10_errstr (rc));
3531 if (!rc && opt.verbose)
3533 log_info (_("writing public key to `%s'\n"),
3534 keydb_get_resource_name (pub_hd));
3535 if (card)
3536 log_info (_("writing secret key stub to `%s'\n"),
3537 keydb_get_resource_name (sec_hd));
3538 else
3539 log_info (_("writing secret key to `%s'\n"),
3540 keydb_get_resource_name (sec_hd));
3543 if (!rc)
3545 rc = keydb_insert_keyblock (pub_hd, pub_root);
3546 if (rc)
3547 log_error (_("error writing public keyring `%s': %s\n"),
3548 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3551 if (!rc)
3553 rc = keydb_insert_keyblock (sec_hd, sec_root);
3554 if (rc)
3555 log_error (_("error writing secret keyring `%s': %s\n"),
3556 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3559 keydb_release (pub_hd);
3560 keydb_release (sec_hd);
3562 if (!rc)
3564 int no_enc_rsa;
3565 PKT_public_key *pk;
3567 no_enc_rsa = (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
3568 && get_parameter_uint (para, pKEYUSAGE)
3569 && !((get_parameter_uint (para, pKEYUSAGE)
3570 & PUBKEY_USAGE_ENC)) );
3572 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3574 keyid_from_pk(pk,pk->main_keyid);
3575 register_trusted_keyid(pk->main_keyid);
3577 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3578 | TRUST_ULTIMATE ));
3580 if (!opt.batch)
3582 tty_printf (_("public and secret key created and signed.\n") );
3583 tty_printf ("\n");
3584 list_keyblock(pub_root,0,1,NULL);
3588 if (!opt.batch
3589 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
3590 || no_enc_rsa )
3591 && !get_parameter (para, pSUBKEYTYPE) )
3593 tty_printf(_("Note that this key cannot be used for "
3594 "encryption. You may want to use\n"
3595 "the command \"--edit-key\" to generate a "
3596 "subkey for this purpose.\n") );
3601 if (rc)
3603 if (opt.batch)
3604 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3605 else
3606 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3607 write_status_error (card? "card_key_generate":"key_generate", rc);
3608 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3610 else
3612 PKT_public_key *pk = find_kbnode (pub_root,
3613 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3614 print_status_key_created (did_sub? 'B':'P', pk,
3615 get_parameter_value (para, pHANDLE));
3617 release_kbnode( pub_root );
3618 release_kbnode( sec_root );
3620 if (pri_sk && !card) /* The unprotected secret key unless we */
3621 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3622 if (sub_sk)
3623 free_secret_key(sub_sk);
3627 /* Add a new subkey to an existing key. Returns true if a new key has
3628 been generated and put into the keyblocks. */
3630 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3632 int okay=0, rc=0;
3633 KBNODE node;
3634 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3635 int algo;
3636 unsigned int use;
3637 u32 expire;
3638 unsigned nbits;
3639 char *passphrase = NULL;
3640 DEK *dek = NULL;
3641 STRING2KEY *s2k = NULL;
3642 u32 cur_time;
3643 int ask_pass = 0;
3644 int canceled;
3646 /* Break out the primary secret key. */
3647 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3648 if( !node )
3650 log_error ("Oops; secret key not found anymore!\n");
3651 goto leave;
3654 /* Make a copy of the sk to keep the protected one in the keyblock. */
3655 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3657 cur_time = make_timestamp();
3659 if (pri_sk->timestamp > cur_time)
3661 ulong d = pri_sk->timestamp - cur_time;
3662 log_info ( d==1 ? _("key has been created %lu second "
3663 "in future (time warp or clock problem)\n")
3664 : _("key has been created %lu seconds "
3665 "in future (time warp or clock problem)\n"), d );
3666 if (!opt.ignore_time_conflict)
3668 rc = G10ERR_TIME_CONFLICT;
3669 goto leave;
3673 if (pri_sk->version < 4)
3675 log_info (_("NOTE: creating subkeys for v3 keys "
3676 "is not OpenPGP compliant\n"));
3677 goto leave;
3680 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3682 tty_printf (_("Secret parts of primary key are not available.\n"));
3683 rc = G10ERR_NO_SECKEY;
3684 goto leave;
3688 /* Unprotect to get the passphrase. */
3689 switch (is_secret_key_protected (pri_sk) )
3691 case -1:
3692 rc = G10ERR_PUBKEY_ALGO;
3693 break;
3694 case 0:
3695 tty_printf (_("This key is not protected.\n"));
3696 break;
3697 case -2:
3698 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3699 ask_pass = 1;
3700 break;
3701 default:
3702 tty_printf (_("Key is protected.\n"));
3703 rc = check_secret_key ( pri_sk, 0 );
3704 if (!rc)
3705 passphrase = get_last_passphrase();
3706 break;
3708 if (rc)
3709 goto leave;
3711 algo = ask_algo (1, NULL, &use);
3712 assert (algo);
3713 nbits = ask_keysize (algo, 0);
3714 expire = ask_expire_interval (0, NULL);
3715 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3716 _("Really create? (y/N) ")))
3717 goto leave;
3719 canceled = 0;
3720 if (ask_pass)
3721 dek = do_ask_passphrase (&s2k, 0, &canceled);
3722 else if (passphrase)
3724 s2k = xmalloc_secure ( sizeof *s2k );
3725 s2k->mode = opt.s2k_mode;
3726 s2k->hash_algo = S2K_DIGEST_ALGO;
3727 set_next_passphrase ( passphrase );
3728 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3729 NULL, NULL );
3732 if (canceled)
3733 rc = GPG_ERR_CANCELED;
3735 if (!rc)
3736 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3737 dek, s2k, &sub_sk, cur_time, expire, 1 );
3738 if (!rc)
3739 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3740 use, cur_time);
3741 if (!rc)
3742 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3743 use, cur_time);
3744 if (!rc)
3746 okay = 1;
3747 write_status_text (STATUS_KEY_CREATED, "S");
3750 leave:
3751 if (rc)
3752 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3753 xfree (passphrase);
3754 xfree (dek);
3755 xfree (s2k);
3756 /* Release the copy of the (now unprotected) secret keys. */
3757 if (pri_sk)
3758 free_secret_key (pri_sk);
3759 if (sub_sk)
3760 free_secret_key (sub_sk);
3761 set_next_passphrase (NULL);
3762 return okay;
3766 #ifdef ENABLE_CARD_SUPPORT
3767 /* Generate a subkey on a card. */
3769 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3770 int keyno, const char *serialno)
3772 int okay=0, rc=0;
3773 KBNODE node;
3774 PKT_secret_key *pri_sk = NULL, *sub_sk;
3775 int algo;
3776 unsigned int use;
3777 u32 expire;
3778 char *passphrase = NULL;
3779 u32 cur_time;
3780 struct para_data_s *para = NULL;
3782 assert (keyno >= 1 && keyno <= 3);
3784 para = xcalloc (1, sizeof *para + strlen (serialno) );
3785 para->key = pSERIALNO;
3786 strcpy (para->u.value, serialno);
3788 /* Break out the primary secret key */
3789 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3790 if (!node)
3792 log_error("Oops; secret key not found anymore!\n");
3793 goto leave;
3796 /* Make a copy of the sk to keep the protected one in the keyblock */
3797 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3799 cur_time = make_timestamp();
3800 if (pri_sk->timestamp > cur_time)
3802 ulong d = pri_sk->timestamp - cur_time;
3803 log_info (d==1 ? _("key has been created %lu second "
3804 "in future (time warp or clock problem)\n")
3805 : _("key has been created %lu seconds "
3806 "in future (time warp or clock problem)\n"), d );
3807 if (!opt.ignore_time_conflict)
3809 rc = G10ERR_TIME_CONFLICT;
3810 goto leave;
3814 if (pri_sk->version < 4)
3816 log_info (_("NOTE: creating subkeys for v3 keys "
3817 "is not OpenPGP compliant\n"));
3818 goto leave;
3821 /* Unprotect to get the passphrase. */
3822 switch( is_secret_key_protected (pri_sk) )
3824 case -1:
3825 rc = G10ERR_PUBKEY_ALGO;
3826 break;
3827 case 0:
3828 tty_printf("This key is not protected.\n");
3829 break;
3830 default:
3831 tty_printf("Key is protected.\n");
3832 rc = check_secret_key( pri_sk, 0 );
3833 if (!rc)
3834 passphrase = get_last_passphrase();
3835 break;
3837 if (rc)
3838 goto leave;
3840 algo = PUBKEY_ALGO_RSA;
3841 expire = ask_expire_interval (0,NULL);
3842 if (keyno == 1)
3843 use = PUBKEY_USAGE_SIG;
3844 else if (keyno == 2)
3845 use = PUBKEY_USAGE_ENC;
3846 else
3847 use = PUBKEY_USAGE_AUTH;
3848 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3849 _("Really create? (y/N) ")))
3850 goto leave;
3852 if (passphrase)
3853 set_next_passphrase (passphrase);
3855 /* Note, that depending on the backend, the card key generation may
3856 update CUR_TIME. */
3857 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3858 &sub_sk, &cur_time, expire, para);
3859 if (!rc)
3860 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3861 use, cur_time);
3862 if (!rc)
3863 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3864 use, cur_time);
3865 if (!rc)
3867 okay = 1;
3868 write_status_text (STATUS_KEY_CREATED, "S");
3871 leave:
3872 if (rc)
3873 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3874 xfree (passphrase);
3875 /* Release the copy of the (now unprotected) secret keys. */
3876 if (pri_sk)
3877 free_secret_key (pri_sk);
3878 set_next_passphrase( NULL );
3879 release_parameter_list (para);
3880 return okay;
3882 #endif /* !ENABLE_CARD_SUPPORT */
3886 * Write a keyblock to an output stream
3888 static int
3889 write_keyblock( IOBUF out, KBNODE node )
3891 for( ; node ; node = node->next )
3893 if(!is_deleted_kbnode(node))
3895 int rc = build_packet( out, node->pkt );
3896 if( rc )
3898 log_error("build_packet(%d) failed: %s\n",
3899 node->pkt->pkttype, g10_errstr(rc) );
3900 return rc;
3905 return 0;
3909 /* Note that timestamp is an in/out arg. */
3910 static int
3911 gen_card_key (int algo, int keyno, int is_primary,
3912 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
3913 u32 *timestamp, u32 expireval, struct para_data_s *para)
3915 #ifdef ENABLE_CARD_SUPPORT
3916 int rc;
3917 const char *s;
3918 struct agent_card_genkey_s info;
3919 PACKET *pkt;
3920 PKT_secret_key *sk;
3921 PKT_public_key *pk;
3923 assert (algo == PUBKEY_ALGO_RSA);
3925 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3926 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
3927 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3928 /* { */
3929 /* tty_printf ("\n"); */
3930 /* log_error ("WARNING: key does already exists!\n"); */
3931 /* tty_printf ("\n"); */
3932 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3933 /* _("Replace existing key? "))) */
3934 /* rc = agent_scd_genkey (&info, keyno, 1); */
3935 /* } */
3937 if (rc)
3939 log_error ("key generation failed: %s\n", gpg_strerror (rc));
3940 return rc;
3942 if ( !info.n || !info.e )
3944 log_error ("communication error with SCD\n");
3945 gcry_mpi_release (info.n);
3946 gcry_mpi_release (info.e);
3947 return gpg_error (GPG_ERR_GENERAL);
3950 if (*timestamp != info.created_at)
3951 log_info ("Note that the key does not use the suggested creation date\n");
3952 *timestamp = info.created_at;
3954 pk = xcalloc (1, sizeof *pk );
3955 sk = xcalloc (1, sizeof *sk );
3956 sk->timestamp = pk->timestamp = info.created_at;
3957 sk->version = pk->version = 4;
3958 if (expireval)
3959 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
3960 sk->pubkey_algo = pk->pubkey_algo = algo;
3961 pk->pkey[0] = info.n;
3962 pk->pkey[1] = info.e;
3963 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
3964 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
3965 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3966 sk->is_protected = 1;
3967 sk->protect.s2k.mode = 1002;
3968 s = get_parameter_value (para, pSERIALNO);
3969 if (s)
3971 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3972 sk->protect.ivlen++, s += 2)
3973 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3976 if( ret_sk )
3977 *ret_sk = sk;
3979 pkt = xcalloc (1,sizeof *pkt);
3980 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
3981 pkt->pkt.public_key = pk;
3982 add_kbnode(pub_root, new_kbnode( pkt ));
3984 pkt = xcalloc (1,sizeof *pkt);
3985 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
3986 pkt->pkt.secret_key = sk;
3987 add_kbnode(sec_root, new_kbnode( pkt ));
3989 return 0;
3990 #else
3991 return -1;
3992 #endif /*!ENABLE_CARD_SUPPORT*/
3997 static int
3998 gen_card_key_with_backup (int algo, int keyno, int is_primary,
3999 KBNODE pub_root, KBNODE sec_root,
4000 u32 timestamp,
4001 u32 expireval, struct para_data_s *para,
4002 const char *backup_dir)
4004 #ifdef ENABLE_CARD_SUPPORT
4005 int rc;
4006 const char *s;
4007 PACKET *pkt;
4008 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
4009 PKT_public_key *pk;
4010 size_t n;
4011 int i;
4012 unsigned int nbits;
4014 /* Get the size of the key directly from the card. */
4016 struct agent_card_info_s info;
4018 memset (&info, 0, sizeof info);
4019 if (!agent_scd_getattr ("KEY-ATTR", &info)
4020 && info.key_attr[1].algo)
4021 nbits = info.key_attr[1].nbits;
4022 else
4023 nbits = 1024; /* All pre-v2.0 cards. */
4024 agent_release_card_info (&info);
4027 /* Create a key of this size in memory. */
4028 rc = generate_raw_key (algo, nbits, timestamp,
4029 &sk_unprotected, &sk_protected);
4030 if (rc)
4031 return rc;
4033 /* Store the key to the card. */
4034 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
4035 if (rc)
4037 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
4038 free_secret_key (sk_unprotected);
4039 free_secret_key (sk_protected);
4040 write_status_error ("save_key_to_card", rc);
4041 return rc;
4044 /* Get rid of the secret key parameters and store the serial numer. */
4045 sk = sk_unprotected;
4046 n = pubkey_get_nskey (sk->pubkey_algo);
4047 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
4049 gcry_mpi_release (sk->skey[i]);
4050 sk->skey[i] = NULL;
4052 i = pubkey_get_npkey (sk->pubkey_algo);
4053 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
4054 sk->is_protected = 1;
4055 sk->protect.s2k.mode = 1002;
4056 s = get_parameter_value (para, pSERIALNO);
4057 assert (s);
4058 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
4059 sk->protect.ivlen++, s += 2)
4060 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
4062 /* Now write the *protected* secret key to the file. */
4064 char name_buffer[50];
4065 char *fname;
4066 IOBUF fp;
4067 mode_t oldmask;
4069 keyid_from_sk (sk, NULL);
4070 snprintf (name_buffer, sizeof name_buffer, "sk_%08lX%08lX.gpg",
4071 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
4073 fname = make_filename (backup_dir, name_buffer, NULL);
4074 oldmask = umask (077);
4075 if (is_secured_filename (fname))
4077 fp = NULL;
4078 errno = EPERM;
4080 else
4081 fp = iobuf_create (fname);
4082 umask (oldmask);
4083 if (!fp)
4085 rc = gpg_error_from_syserror ();
4086 log_error (_("can't create backup file `%s': %s\n"),
4087 fname, strerror(errno) );
4088 xfree (fname);
4089 free_secret_key (sk_unprotected);
4090 free_secret_key (sk_protected);
4091 return rc;
4094 pkt = xcalloc (1, sizeof *pkt);
4095 pkt->pkttype = PKT_SECRET_KEY;
4096 pkt->pkt.secret_key = sk_protected;
4097 sk_protected = NULL;
4099 rc = build_packet (fp, pkt);
4100 if (rc)
4102 log_error("build packet failed: %s\n", g10_errstr(rc) );
4103 iobuf_cancel (fp);
4105 else
4107 unsigned char array[MAX_FINGERPRINT_LEN];
4108 char *fprbuf, *p;
4110 iobuf_close (fp);
4111 iobuf_ioctl (NULL, 2, 0, (char*)fname);
4112 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
4114 fingerprint_from_sk (sk, array, &n);
4115 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4116 for (i=0; i < n ; i++, p += 2)
4117 sprintf (p, "%02X", array[i]);
4118 *p++ = ' ';
4119 *p = 0;
4121 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4122 fprbuf,
4123 fname, strlen (fname),
4125 xfree (fprbuf);
4127 free_packet (pkt);
4128 xfree (pkt);
4129 xfree (fname);
4130 if (rc)
4132 free_secret_key (sk_unprotected);
4133 return rc;
4137 /* Create the public key from the secret key. */
4138 pk = xcalloc (1, sizeof *pk );
4139 pk->timestamp = sk->timestamp;
4140 pk->version = sk->version;
4141 if (expireval)
4142 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4143 pk->pubkey_algo = sk->pubkey_algo;
4144 n = pubkey_get_npkey (sk->pubkey_algo);
4145 for (i=0; i < n; i++)
4146 pk->pkey[i] = mpi_copy (sk->skey[i]);
4148 /* Build packets and add them to the node lists. */
4149 pkt = xcalloc (1,sizeof *pkt);
4150 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4151 pkt->pkt.public_key = pk;
4152 add_kbnode(pub_root, new_kbnode( pkt ));
4154 pkt = xcalloc (1,sizeof *pkt);
4155 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4156 pkt->pkt.secret_key = sk;
4157 add_kbnode(sec_root, new_kbnode( pkt ));
4159 return 0;
4160 #else
4161 return -1;
4162 #endif /*!ENABLE_CARD_SUPPORT*/
4166 #ifdef ENABLE_CARD_SUPPORT
4168 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
4170 int rc;
4171 unsigned char *rsa_n = NULL;
4172 unsigned char *rsa_e = NULL;
4173 unsigned char *rsa_p = NULL;
4174 unsigned char *rsa_q = NULL;
4175 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4176 unsigned char *sexp = NULL;
4177 unsigned char *p;
4178 char numbuf[55], numbuf2[50];
4180 assert (is_RSA (sk->pubkey_algo));
4181 assert (!sk->is_protected);
4183 /* Copy the parameters into straight buffers. */
4184 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4185 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4186 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4187 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4188 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4190 rc = G10ERR_INV_ARG;
4191 goto leave;
4194 /* Put the key into an S-expression. */
4195 sexp = p = xmalloc_secure (30
4196 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4197 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4199 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4200 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4201 p = stpcpy (p, numbuf);
4202 memcpy (p, rsa_n, rsa_n_len);
4203 p += rsa_n_len;
4205 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4206 p = stpcpy (p, numbuf);
4207 memcpy (p, rsa_e, rsa_e_len);
4208 p += rsa_e_len;
4210 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4211 p = stpcpy (p, numbuf);
4212 memcpy (p, rsa_p, rsa_p_len);
4213 p += rsa_p_len;
4215 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4216 p = stpcpy (p, numbuf);
4217 memcpy (p, rsa_q, rsa_q_len);
4218 p += rsa_q_len;
4220 p = stpcpy (p,"))(10:created-at");
4221 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4222 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4223 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4225 /* Fixme: Unfortunately we don't have the serialnumber available -
4226 thus we can't pass it down to the agent. */
4227 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4229 leave:
4230 xfree (sexp);
4231 xfree (rsa_n);
4232 xfree (rsa_e);
4233 xfree (rsa_p);
4234 xfree (rsa_q);
4235 return rc;
4237 #endif /*ENABLE_CARD_SUPPORT*/