2008-02-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / keygen.c
blob48a7fa271d772e4b272999ee51f77b082bf747e6
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 use_files;
96 struct {
97 char *fname;
98 char *newfname;
99 IOBUF stream;
100 armor_filter_context_t *afx;
101 } pub;
102 struct {
103 char *fname;
104 char *newfname;
105 IOBUF stream;
106 armor_filter_context_t *afx;
107 } sec;
111 struct opaque_data_usage_and_pk {
112 unsigned int usage;
113 PKT_public_key *pk;
117 static int prefs_initialized = 0;
118 static byte sym_prefs[MAX_PREFS];
119 static int nsym_prefs;
120 static byte hash_prefs[MAX_PREFS];
121 static int nhash_prefs;
122 static byte zip_prefs[MAX_PREFS];
123 static int nzip_prefs;
124 static int mdc_available,ks_modify;
126 static void do_generate_keypair( struct para_data_s *para,
127 struct output_control_s *outctrl, int card );
128 static int write_keyblock( IOBUF out, KBNODE node );
129 static int gen_card_key (int algo, int keyno, int is_primary,
130 KBNODE pub_root, KBNODE sec_root,
131 PKT_secret_key **ret_sk,
132 u32 *timestamp,
133 u32 expireval, struct para_data_s *para);
134 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
135 KBNODE pub_root, KBNODE sec_root,
136 u32 timestamp,
137 u32 expireval, struct para_data_s *para,
138 const char *backup_dir);
141 static void
142 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
144 byte array[MAX_FINGERPRINT_LEN], *s;
145 char *buf, *p;
146 size_t i, n;
148 if (!handle)
149 handle = "";
151 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
153 p = buf;
154 if (letter || pk)
156 *p++ = letter;
157 *p++ = ' ';
158 fingerprint_from_pk (pk, array, &n);
159 s = array;
160 for (i=0; i < n ; i++, s++, p += 2)
161 sprintf (p, "%02X", *s);
163 if (*handle)
165 *p++ = ' ';
166 for (i=0; handle[i] && i < 100; i++)
167 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
169 *p = 0;
170 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
171 buf);
172 xfree (buf);
175 static void
176 print_status_key_not_created (const char *handle)
178 print_status_key_created (0, NULL, handle);
183 static void
184 write_uid( KBNODE root, const char *s )
186 PACKET *pkt = xmalloc_clear(sizeof *pkt );
187 size_t n = strlen(s);
189 pkt->pkttype = PKT_USER_ID;
190 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
191 pkt->pkt.user_id->len = n;
192 pkt->pkt.user_id->ref = 1;
193 strcpy(pkt->pkt.user_id->name, s);
194 add_kbnode( root, new_kbnode( pkt ) );
197 static void
198 do_add_key_flags (PKT_signature *sig, unsigned int use)
200 byte buf[1];
202 buf[0] = 0;
204 /* The spec says that all primary keys MUST be able to certify. */
205 if(sig->sig_class!=0x18)
206 buf[0] |= 0x01;
208 if (use & PUBKEY_USAGE_SIG)
209 buf[0] |= 0x02;
210 if (use & PUBKEY_USAGE_ENC)
211 buf[0] |= 0x04 | 0x08;
212 if (use & PUBKEY_USAGE_AUTH)
213 buf[0] |= 0x20;
215 if (!buf[0])
216 return;
218 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
223 keygen_add_key_expire( PKT_signature *sig, void *opaque )
225 PKT_public_key *pk = opaque;
226 byte buf[8];
227 u32 u;
229 if( pk->expiredate ) {
230 if(pk->expiredate > pk->timestamp)
231 u= pk->expiredate - pk->timestamp;
232 else
233 u= 1;
235 buf[0] = (u >> 24) & 0xff;
236 buf[1] = (u >> 16) & 0xff;
237 buf[2] = (u >> 8) & 0xff;
238 buf[3] = u & 0xff;
239 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
241 else
243 /* Make sure we don't leave a key expiration subpacket lying
244 around */
245 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
248 return 0;
251 static int
252 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
254 struct opaque_data_usage_and_pk *oduap = opaque;
256 do_add_key_flags (sig, oduap->usage);
257 return keygen_add_key_expire (sig, oduap->pk);
260 static int
261 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
263 int i;
265 for (i=0; i < *nbuf; i++ )
266 if (buf[i] == val)
268 log_info (_("preference `%s' duplicated\n"), item);
269 return -1;
272 if (*nbuf >= MAX_PREFS)
274 if(type==1)
275 log_info(_("too many cipher preferences\n"));
276 else if(type==2)
277 log_info(_("too many digest preferences\n"));
278 else if(type==3)
279 log_info(_("too many compression preferences\n"));
280 else
281 BUG();
283 return -1;
286 buf[(*nbuf)++] = val;
287 return 0;
291 * Parse the supplied string and use it to set the standard
292 * preferences. The string may be in a form like the one printed by
293 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
294 * cipher/hash/compress names. Use NULL to set the default
295 * preferences. Returns: 0 = okay
298 keygen_set_std_prefs (const char *string,int personal)
300 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
301 int nsym=0, nhash=0, nzip=0, val, rc=0;
302 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
303 char dummy_string[45+1]; /* Enough for 15 items. */
305 if (!string || !ascii_strcasecmp (string, "default"))
307 if (opt.def_preference_list)
308 string=opt.def_preference_list;
309 else
311 dummy_string[0]='\0';
313 /* The rationale why we use the order AES256,192,128 is
314 for compatibility reasons with PGP. If gpg would
315 define AES128 first, we would get the somewhat
316 confusing situation:
318 gpg -r pgpkey -r gpgkey ---gives--> AES256
319 gpg -r gpgkey -r pgpkey ---gives--> AES
321 Note that by using --personal-cipher-preferences it is
322 possible to prefer AES128.
325 /* Make sure we do not add more than 15 items here, as we
326 could overflow the size of dummy_string. We currently
327 have at most 12. */
328 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
329 strcat(dummy_string,"S9 ");
330 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
331 strcat(dummy_string,"S8 ");
332 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
333 strcat(dummy_string,"S7 ");
334 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
335 strcat(dummy_string,"S3 ");
336 strcat(dummy_string,"S2 "); /* 3DES */
337 /* If we have it, IDEA goes *after* 3DES so it won't be
338 used unless we're encrypting along with a V3 key.
339 Ideally, we would only put the S1 preference in if the
340 key was RSA and <=2048 bits, as that is what won't
341 break PGP2, but that is difficult with the current
342 code, and not really worth checking as a non-RSA <=2048
343 bit key wouldn't be usable by PGP2 anyway. -dms */
344 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
345 strcat(dummy_string,"S1 ");
347 /* SHA-1 */
348 strcat(dummy_string,"H2 ");
350 if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256))
351 strcat(dummy_string,"H8 ");
353 /* RIPEMD160 */
354 strcat(dummy_string,"H3 ");
356 /* ZLIB */
357 strcat(dummy_string,"Z2 ");
359 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
360 strcat(dummy_string,"Z3 ");
362 /* ZIP */
363 strcat(dummy_string,"Z1");
365 string=dummy_string;
368 else if (!ascii_strcasecmp (string, "none"))
369 string = "";
371 if(strlen(string))
373 char *tok,*prefstring;
375 prefstring=xstrdup(string); /* need a writable string! */
377 while((tok=strsep(&prefstring," ,")))
379 if((val=string_to_cipher_algo (tok)))
381 if(set_one_pref(val,1,tok,sym,&nsym))
382 rc=-1;
384 else if((val=string_to_digest_algo (tok)))
386 if(set_one_pref(val,2,tok,hash,&nhash))
387 rc=-1;
389 else if((val=string_to_compress_algo(tok))>-1)
391 if(set_one_pref(val,3,tok,zip,&nzip))
392 rc=-1;
394 else if (ascii_strcasecmp(tok,"mdc")==0)
395 mdc=1;
396 else if (ascii_strcasecmp(tok,"no-mdc")==0)
397 mdc=0;
398 else if (ascii_strcasecmp(tok,"ks-modify")==0)
399 modify=1;
400 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
401 modify=0;
402 else
404 log_info (_("invalid item `%s' in preference string\n"),tok);
406 /* Complain if IDEA is not available. */
407 if(ascii_strcasecmp(tok,"s1")==0
408 || ascii_strcasecmp(tok,"idea")==0)
409 idea_cipher_warn(1);
411 rc=-1;
415 xfree(prefstring);
418 if(!rc)
420 if(personal)
422 if(personal==PREFTYPE_SYM)
424 xfree(opt.personal_cipher_prefs);
426 if(nsym==0)
427 opt.personal_cipher_prefs=NULL;
428 else
430 int i;
432 opt.personal_cipher_prefs=
433 xmalloc(sizeof(prefitem_t *)*(nsym+1));
435 for (i=0; i<nsym; i++)
437 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
438 opt.personal_cipher_prefs[i].value = sym[i];
441 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
442 opt.personal_cipher_prefs[i].value = 0;
445 else if(personal==PREFTYPE_HASH)
447 xfree(opt.personal_digest_prefs);
449 if(nhash==0)
450 opt.personal_digest_prefs=NULL;
451 else
453 int i;
455 opt.personal_digest_prefs=
456 xmalloc(sizeof(prefitem_t *)*(nhash+1));
458 for (i=0; i<nhash; i++)
460 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
461 opt.personal_digest_prefs[i].value = hash[i];
464 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
465 opt.personal_digest_prefs[i].value = 0;
468 else if(personal==PREFTYPE_ZIP)
470 xfree(opt.personal_compress_prefs);
472 if(nzip==0)
473 opt.personal_compress_prefs=NULL;
474 else
476 int i;
478 opt.personal_compress_prefs=
479 xmalloc(sizeof(prefitem_t *)*(nzip+1));
481 for (i=0; i<nzip; i++)
483 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
484 opt.personal_compress_prefs[i].value = zip[i];
487 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
488 opt.personal_compress_prefs[i].value = 0;
492 else
494 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
495 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
496 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
497 mdc_available = mdc;
498 ks_modify = modify;
499 prefs_initialized = 1;
503 return rc;
506 /* Return a fake user ID containing the preferences. Caller must
507 free. */
508 PKT_user_id *keygen_get_std_prefs(void)
510 int i,j=0;
511 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
513 if(!prefs_initialized)
514 keygen_set_std_prefs(NULL,0);
516 uid->ref=1;
518 uid->prefs=xmalloc((sizeof(prefitem_t *)*
519 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
521 for(i=0;i<nsym_prefs;i++,j++)
523 uid->prefs[j].type=PREFTYPE_SYM;
524 uid->prefs[j].value=sym_prefs[i];
527 for(i=0;i<nhash_prefs;i++,j++)
529 uid->prefs[j].type=PREFTYPE_HASH;
530 uid->prefs[j].value=hash_prefs[i];
533 for(i=0;i<nzip_prefs;i++,j++)
535 uid->prefs[j].type=PREFTYPE_ZIP;
536 uid->prefs[j].value=zip_prefs[i];
539 uid->prefs[j].type=PREFTYPE_NONE;
540 uid->prefs[j].value=0;
542 uid->flags.mdc=mdc_available;
543 uid->flags.ks_modify=ks_modify;
545 return uid;
548 static void
549 add_feature_mdc (PKT_signature *sig,int enabled)
551 const byte *s;
552 size_t n;
553 int i;
554 char *buf;
556 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
557 /* Already set or cleared */
558 if (s && n &&
559 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
560 return;
562 if (!s || !n) { /* create a new one */
563 n = 1;
564 buf = xmalloc_clear (n);
566 else {
567 buf = xmalloc (n);
568 memcpy (buf, s, n);
571 if(enabled)
572 buf[0] |= 0x01; /* MDC feature */
573 else
574 buf[0] &= ~0x01;
576 /* Are there any bits set? */
577 for(i=0;i<n;i++)
578 if(buf[i]!=0)
579 break;
581 if(i==n)
582 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
583 else
584 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
586 xfree (buf);
589 static void
590 add_keyserver_modify (PKT_signature *sig,int enabled)
592 const byte *s;
593 size_t n;
594 int i;
595 char *buf;
597 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
598 enabled=!enabled;
600 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
601 /* Already set or cleared */
602 if (s && n &&
603 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
604 return;
606 if (!s || !n) { /* create a new one */
607 n = 1;
608 buf = xmalloc_clear (n);
610 else {
611 buf = xmalloc (n);
612 memcpy (buf, s, n);
615 if(enabled)
616 buf[0] |= 0x80; /* no-modify flag */
617 else
618 buf[0] &= ~0x80;
620 /* Are there any bits set? */
621 for(i=0;i<n;i++)
622 if(buf[i]!=0)
623 break;
625 if(i==n)
626 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
627 else
628 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
630 xfree (buf);
634 keygen_upd_std_prefs( PKT_signature *sig, void *opaque )
636 if (!prefs_initialized)
637 keygen_set_std_prefs (NULL, 0);
639 if (nsym_prefs)
640 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
641 else
643 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
644 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
647 if (nhash_prefs)
648 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
649 else
651 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
652 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
655 if (nzip_prefs)
656 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
657 else
659 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
660 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
663 /* Make sure that the MDC feature flag is set if needed */
664 add_feature_mdc (sig,mdc_available);
665 add_keyserver_modify (sig,ks_modify);
666 keygen_add_keyserver_url(sig,NULL);
668 return 0;
672 /****************
673 * Add preference to the self signature packet.
674 * This is only called for packets with version > 3.
678 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
680 PKT_public_key *pk = opaque;
682 do_add_key_flags (sig, pk->pubkey_usage);
683 keygen_add_key_expire( sig, opaque );
684 keygen_upd_std_prefs (sig, opaque);
685 keygen_add_keyserver_url(sig,NULL);
687 return 0;
691 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
693 const char *url=opaque;
695 if(!url)
696 url=opt.def_keyserver_url;
698 if(url)
699 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
700 else
701 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
703 return 0;
707 keygen_add_notations(PKT_signature *sig,void *opaque)
709 struct notation *notation;
711 /* We always start clean */
712 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
713 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
714 sig->flags.notation=0;
716 for(notation=opaque;notation;notation=notation->next)
717 if(!notation->flags.ignore)
719 unsigned char *buf;
720 unsigned int n1,n2;
722 n1=strlen(notation->name);
723 if(notation->altvalue)
724 n2=strlen(notation->altvalue);
725 else if(notation->bdat)
726 n2=notation->blen;
727 else
728 n2=strlen(notation->value);
730 buf = xmalloc( 8 + n1 + n2 );
732 /* human readable or not */
733 buf[0] = notation->bdat?0:0x80;
734 buf[1] = buf[2] = buf[3] = 0;
735 buf[4] = n1 >> 8;
736 buf[5] = n1;
737 buf[6] = n2 >> 8;
738 buf[7] = n2;
739 memcpy(buf+8, notation->name, n1 );
740 if(notation->altvalue)
741 memcpy(buf+8+n1, notation->altvalue, n2 );
742 else if(notation->bdat)
743 memcpy(buf+8+n1, notation->bdat, n2 );
744 else
745 memcpy(buf+8+n1, notation->value, n2 );
746 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
747 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
748 buf, 8+n1+n2 );
749 xfree(buf);
752 return 0;
756 keygen_add_revkey(PKT_signature *sig, void *opaque)
758 struct revocation_key *revkey=opaque;
759 byte buf[2+MAX_FINGERPRINT_LEN];
761 buf[0]=revkey->class;
762 buf[1]=revkey->algid;
763 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
765 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
767 /* All sigs with revocation keys set are nonrevocable */
768 sig->flags.revocable=0;
769 buf[0] = 0;
770 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
772 parse_revkeys(sig);
774 return 0;
779 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
780 signature creation time. */
782 make_backsig (PKT_signature *sig,PKT_public_key *pk,
783 PKT_public_key *sub_pk,PKT_secret_key *sub_sk,
784 u32 timestamp)
786 PKT_signature *backsig;
787 int rc;
789 cache_public_key(sub_pk);
791 rc = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_sk, 0x19,
792 0, 0, timestamp, 0, NULL, NULL);
793 if(rc)
794 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
795 else
797 /* Get it into a binary packed form. */
798 IOBUF backsig_out=iobuf_temp();
799 PACKET backsig_pkt;
801 init_packet(&backsig_pkt);
802 backsig_pkt.pkttype=PKT_SIGNATURE;
803 backsig_pkt.pkt.signature=backsig;
804 rc=build_packet(backsig_out,&backsig_pkt);
805 free_packet(&backsig_pkt);
806 if(rc)
807 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
808 else
810 size_t pktlen=0;
811 byte *buf=iobuf_get_temp_buffer(backsig_out);
813 /* Remove the packet header */
814 if(buf[0]&0x40)
816 if(buf[1]<192)
818 pktlen=buf[1];
819 buf+=2;
821 else if(buf[1]<224)
823 pktlen=(buf[1]-192)*256;
824 pktlen+=buf[2]+192;
825 buf+=3;
827 else if(buf[1]==255)
829 pktlen =buf[2] << 24;
830 pktlen|=buf[3] << 16;
831 pktlen|=buf[4] << 8;
832 pktlen|=buf[5];
833 buf+=6;
835 else
836 BUG();
838 else
840 int mark=1;
842 switch(buf[0]&3)
844 case 3:
845 BUG();
846 break;
848 case 2:
849 pktlen =buf[mark++] << 24;
850 pktlen|=buf[mark++] << 16;
852 case 1:
853 pktlen|=buf[mark++] << 8;
855 case 0:
856 pktlen|=buf[mark++];
859 buf+=mark;
862 /* Now make the binary blob into a subpacket. */
863 build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
865 iobuf_close(backsig_out);
869 return rc;
873 static int
874 write_direct_sig (KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
875 struct revocation_key *revkey, u32 timestamp)
877 PACKET *pkt;
878 PKT_signature *sig;
879 int rc=0;
880 KBNODE node;
881 PKT_public_key *pk;
883 if( opt.verbose )
884 log_info(_("writing direct signature\n"));
886 /* Get the pk packet from the pub_tree. */
887 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
888 if( !node )
889 BUG();
890 pk = node->pkt->pkt.public_key;
892 /* We have to cache the key, so that the verification of the
893 signature creation is able to retrieve the public key. */
894 cache_public_key (pk);
896 /* Make the signature. */
897 rc = make_keysig_packet (&sig,pk,NULL,NULL,sk,0x1F,
898 0, 0, timestamp, 0,
899 keygen_add_revkey, revkey);
900 if( rc )
902 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
903 return rc;
906 pkt = xmalloc_clear( sizeof *pkt );
907 pkt->pkttype = PKT_SIGNATURE;
908 pkt->pkt.signature = sig;
909 add_kbnode( root, new_kbnode( pkt ) );
910 return rc;
914 static int
915 write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
916 unsigned int use, u32 timestamp )
918 PACKET *pkt;
919 PKT_signature *sig;
920 PKT_user_id *uid;
921 int rc=0;
922 KBNODE node;
923 PKT_public_key *pk;
925 if( opt.verbose )
926 log_info(_("writing self signature\n"));
928 /* Get the uid packet from the list. */
929 node = find_kbnode( pub_root, PKT_USER_ID );
930 if( !node )
931 BUG(); /* No user id packet in tree. */
932 uid = node->pkt->pkt.user_id;
934 /* Get the pk packet from the pub_tree. */
935 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
936 if( !node )
937 BUG();
938 pk = node->pkt->pkt.public_key;
939 pk->pubkey_usage = use;
941 /* We have to cache the key, so that the verification of the
942 signature creation is able to retrieve the public key. */
943 cache_public_key (pk);
945 /* Make the signature. */
946 rc = make_keysig_packet (&sig, pk, uid, NULL, sk, 0x13,
947 0, 0, timestamp, 0,
948 keygen_add_std_prefs, pk);
949 if( rc )
951 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
952 return rc;
955 pkt = xmalloc_clear( sizeof *pkt );
956 pkt->pkttype = PKT_SIGNATURE;
957 pkt->pkt.signature = sig;
958 add_kbnode( sec_root, new_kbnode( pkt ) );
960 pkt = xmalloc_clear( sizeof *pkt );
961 pkt->pkttype = PKT_SIGNATURE;
962 pkt->pkt.signature = copy_signature(NULL,sig);
963 add_kbnode( pub_root, new_kbnode( pkt ) );
964 return rc;
968 /* Write the key binding signature. If TIMESTAMP is not NULL use the
969 signature creation times. */
970 static int
971 write_keybinding (KBNODE root, KBNODE pub_root,
972 PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
973 unsigned int use, u32 timestamp)
975 PACKET *pkt;
976 PKT_signature *sig;
977 int rc=0;
978 KBNODE node;
979 PKT_public_key *pri_pk, *sub_pk;
980 struct opaque_data_usage_and_pk oduap;
982 if ( opt.verbose )
983 log_info(_("writing key binding signature\n"));
985 /* Get the pk packet from the pub_tree. */
986 node = find_kbnode ( pub_root, PKT_PUBLIC_KEY );
987 if ( !node )
988 BUG();
989 pri_pk = node->pkt->pkt.public_key;
991 /* We have to cache the key, so that the verification of the
992 * signature creation is able to retrieve the public key. */
993 cache_public_key (pri_pk);
995 /* Find the last subkey. */
996 sub_pk = NULL;
997 for (node=pub_root; node; node = node->next )
999 if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
1000 sub_pk = node->pkt->pkt.public_key;
1002 if (!sub_pk)
1003 BUG();
1005 /* Make the signature. */
1006 oduap.usage = use;
1007 oduap.pk = sub_pk;
1008 rc = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18,
1009 0, 0, timestamp, 0,
1010 keygen_add_key_flags_and_expire, &oduap );
1011 if (rc)
1013 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc) );
1014 return rc;
1017 /* Make a backsig. */
1018 if (use&PUBKEY_USAGE_SIG)
1020 rc = make_backsig (sig, pri_pk, sub_pk, sub_sk, timestamp);
1021 if (rc)
1022 return rc;
1025 pkt = xmalloc_clear ( sizeof *pkt );
1026 pkt->pkttype = PKT_SIGNATURE;
1027 pkt->pkt.signature = sig;
1028 add_kbnode (root, new_kbnode (pkt) );
1029 return rc;
1034 static int
1035 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1036 const char *topname, const char *elems)
1038 gcry_sexp_t list, l2;
1039 const char *s;
1040 int i, idx;
1041 int rc = 0;
1043 list = gcry_sexp_find_token (sexp, topname, 0);
1044 if (!list)
1045 return gpg_error (GPG_ERR_INV_OBJ);
1046 l2 = gcry_sexp_cadr (list);
1047 gcry_sexp_release (list);
1048 list = l2;
1049 if (!list)
1050 return gpg_error (GPG_ERR_NO_OBJ);
1052 for (idx=0,s=elems; *s; s++, idx++)
1054 l2 = gcry_sexp_find_token (list, s, 1);
1055 if (!l2)
1057 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1058 goto leave;
1060 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1061 gcry_sexp_release (l2);
1062 if (!array[idx])
1064 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1065 goto leave;
1068 gcry_sexp_release (list);
1070 leave:
1071 if (rc)
1073 for (i=0; i<idx; i++)
1075 xfree (array[i]);
1076 array[i] = NULL;
1078 gcry_sexp_release (list);
1080 return rc;
1084 static int
1085 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
1087 int rc = 0;
1089 if (dek)
1091 sk->protect.algo = dek->algo;
1092 sk->protect.s2k = *s2k;
1093 rc = protect_secret_key (sk, dek);
1094 if (rc)
1095 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
1098 return rc;
1101 static void
1102 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
1104 #if 0 /* Not used anymore */
1105 size_t n;
1106 char *buf;
1108 if (misc_key_info)
1110 /* DSA: don't know whether it makes sense to have the factors, so for now
1111 we store them in the secret keyring (but they are not secret)
1112 p = 2 * q * f1 * f2 * ... * fn
1113 We store only f1 to f_n-1; fn can be calculated because p and q
1114 are known. */
1115 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
1116 buf = xmalloc (n+4);
1117 strcpy (buf, "#::");
1118 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
1119 if (n)
1121 n += 3;
1122 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
1124 xfree (buf);
1125 gcry_sexp_release (misc_key_info);
1127 #endif
1131 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1132 time to be put into the key structure. */
1133 static int
1134 gen_elg (int algo, unsigned int nbits,
1135 KBNODE pub_root, KBNODE sec_root, DEK *dek,
1136 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1137 u32 timestamp, u32 expireval, int is_subkey)
1139 int rc;
1140 PACKET *pkt;
1141 PKT_secret_key *sk;
1142 PKT_public_key *pk;
1143 gcry_sexp_t s_parms, s_key;
1144 gcry_sexp_t misc_key_info;
1146 assert( is_ELGAMAL(algo) );
1148 if (nbits < 512)
1150 nbits = 1024;
1151 log_info (_("keysize invalid; using %u bits\n"), nbits );
1154 if ((nbits % 32))
1156 nbits = ((nbits + 31) / 32) * 32;
1157 log_info (_("keysize rounded up to %u bits\n"), nbits );
1161 rc = gcry_sexp_build ( &s_parms, NULL,
1162 "(genkey(%s(nbits %d)))",
1163 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1164 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1165 (int)nbits);
1166 if (rc)
1167 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1169 rc = gcry_pk_genkey (&s_key, s_parms);
1170 gcry_sexp_release (s_parms);
1171 if (rc)
1173 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1174 return rc;
1177 sk = xmalloc_clear( sizeof *sk );
1178 pk = xmalloc_clear( sizeof *pk );
1179 sk->timestamp = pk->timestamp = timestamp;
1180 sk->version = pk->version = 4;
1181 if (expireval)
1183 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1185 sk->pubkey_algo = pk->pubkey_algo = algo;
1187 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
1188 if (rc)
1190 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1191 gcry_sexp_release (s_key);
1192 free_secret_key (sk);
1193 free_public_key (pk);
1194 return rc;
1196 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
1197 if (rc)
1199 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1200 gcry_sexp_release (s_key);
1201 free_secret_key (sk);
1202 free_public_key (pk);
1203 return rc;
1205 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1206 gcry_sexp_release (s_key);
1208 sk->is_protected = 0;
1209 sk->protect.algo = 0;
1211 sk->csum = checksum_mpi (sk->skey[3]);
1212 if (ret_sk) /* Return an unprotected version of the sk. */
1213 *ret_sk = copy_secret_key ( NULL, sk );
1215 rc = genhelp_protect (dek, s2k, sk);
1216 if (rc)
1218 free_public_key (pk);
1219 free_secret_key (sk);
1220 gcry_sexp_release (misc_key_info);
1221 return rc;
1224 pkt = xmalloc_clear (sizeof *pkt);
1225 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1226 pkt->pkt.public_key = pk;
1227 add_kbnode (pub_root, new_kbnode( pkt ));
1229 /* Don't know whether it makes sense to have access to the factors,
1230 so for now we store them in the secret keyring (but they are not
1231 secret). */
1232 pkt = xmalloc_clear (sizeof *pkt);
1233 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1234 pkt->pkt.secret_key = sk;
1235 add_kbnode (sec_root, new_kbnode( pkt ));
1237 genhelp_factors (misc_key_info, sec_root);
1239 return 0;
1243 /****************
1244 * Generate a DSA key
1246 static int
1247 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1248 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1249 u32 timestamp, u32 expireval, int is_subkey)
1251 int rc;
1252 PACKET *pkt;
1253 PKT_secret_key *sk;
1254 PKT_public_key *pk;
1255 gcry_sexp_t s_parms, s_key;
1256 gcry_sexp_t misc_key_info;
1257 unsigned int qbits;
1259 if ( nbits < 512 || (!opt.flags.dsa2 && nbits > 1024))
1261 nbits = 1024;
1262 log_info(_("keysize invalid; using %u bits\n"), nbits );
1264 else if ( nbits > 3072 )
1266 nbits = 3072;
1267 log_info(_("keysize invalid; using %u bits\n"), nbits );
1270 if( (nbits % 64) )
1272 nbits = ((nbits + 63) / 64) * 64;
1273 log_info(_("keysize rounded up to %u bits\n"), nbits );
1277 Figure out a q size based on the key size. FIPS 180-3 says:
1279 L = 1024, N = 160
1280 L = 2048, N = 224
1281 L = 2048, N = 256
1282 L = 3072, N = 256
1284 2048/256 is an odd pair since there is also a 2048/224 and
1285 3072/256. Matching sizes is not a very exact science.
1287 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1288 but less than 2048, and 160 for 1024 (DSA1).
1291 if (nbits > 2048)
1292 qbits = 256;
1293 else if ( nbits > 1024)
1294 qbits = 224;
1295 else
1296 qbits = 160;
1298 if (qbits != 160 )
1299 log_info (_("WARNING: some OpenPGP programs can't"
1300 " handle a DSA key with this digest size\n"));
1302 rc = gcry_sexp_build (&s_parms, NULL,
1303 "(genkey(dsa(nbits %d)(qbits %d)))",
1304 (int)nbits, (int)qbits);
1305 if (rc)
1306 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1308 rc = gcry_pk_genkey (&s_key, s_parms);
1309 gcry_sexp_release (s_parms);
1310 if (rc)
1312 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1313 return rc;
1316 sk = xmalloc_clear( sizeof *sk );
1317 pk = xmalloc_clear( sizeof *pk );
1318 sk->timestamp = pk->timestamp = timestamp;
1319 sk->version = pk->version = 4;
1320 if (expireval)
1321 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1322 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1324 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1325 if (rc)
1327 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1328 gcry_sexp_release (s_key);
1329 free_public_key(pk);
1330 free_secret_key(sk);
1331 return rc;
1333 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1334 if (rc)
1336 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1337 gcry_sexp_release (s_key);
1338 free_public_key(pk);
1339 free_secret_key(sk);
1340 return rc;
1342 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1343 gcry_sexp_release (s_key);
1345 sk->is_protected = 0;
1346 sk->protect.algo = 0;
1348 sk->csum = checksum_mpi ( sk->skey[4] );
1349 if( ret_sk ) /* return an unprotected version of the sk */
1350 *ret_sk = copy_secret_key( NULL, sk );
1352 rc = genhelp_protect (dek, s2k, sk);
1353 if (rc)
1355 free_public_key (pk);
1356 free_secret_key (sk);
1357 gcry_sexp_release (misc_key_info);
1358 return rc;
1361 pkt = xmalloc_clear(sizeof *pkt);
1362 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1363 pkt->pkt.public_key = pk;
1364 add_kbnode(pub_root, new_kbnode( pkt ));
1366 /* Don't know whether it makes sense to have the factors, so for now
1367 * we store them in the secret keyring (but they are not secret)
1368 * p = 2 * q * f1 * f2 * ... * fn
1369 * We store only f1 to f_n-1; fn can be calculated because p and q
1370 * are known.
1372 pkt = xmalloc_clear(sizeof *pkt);
1373 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1374 pkt->pkt.secret_key = sk;
1375 add_kbnode(sec_root, new_kbnode( pkt ));
1377 genhelp_factors (misc_key_info, sec_root);
1379 return 0;
1384 * Generate an RSA key.
1386 static int
1387 gen_rsa (int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1388 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1389 u32 timestamp, u32 expireval, int is_subkey)
1391 int rc;
1392 PACKET *pkt;
1393 PKT_secret_key *sk;
1394 PKT_public_key *pk;
1395 gcry_sexp_t s_parms, s_key;
1397 assert (is_RSA(algo));
1399 if (nbits < 1024)
1401 nbits = 1024;
1402 log_info (_("keysize invalid; using %u bits\n"), nbits );
1405 if ((nbits % 32))
1407 nbits = ((nbits + 31) / 32) * 32;
1408 log_info (_("keysize rounded up to %u bits\n"), nbits );
1411 rc = gcry_sexp_build (&s_parms, NULL,
1412 "(genkey(rsa(nbits %d)))",
1413 (int)nbits);
1414 if (rc)
1415 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1417 rc = gcry_pk_genkey (&s_key, s_parms);
1418 gcry_sexp_release (s_parms);
1419 if (rc)
1421 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1422 return rc;
1425 sk = xmalloc_clear( sizeof *sk );
1426 pk = xmalloc_clear( sizeof *pk );
1427 sk->timestamp = pk->timestamp = timestamp;
1428 sk->version = pk->version = 4;
1429 if (expireval)
1431 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1433 sk->pubkey_algo = pk->pubkey_algo = algo;
1435 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1436 if (rc)
1438 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1439 gcry_sexp_release (s_key);
1440 free_public_key(pk);
1441 free_secret_key(sk);
1442 return rc;
1444 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1445 if (rc)
1447 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1448 gcry_sexp_release (s_key);
1449 free_public_key(pk);
1450 free_secret_key(sk);
1451 return rc;
1453 gcry_sexp_release (s_key);
1455 sk->is_protected = 0;
1456 sk->protect.algo = 0;
1458 sk->csum = checksum_mpi (sk->skey[2] );
1459 sk->csum += checksum_mpi (sk->skey[3] );
1460 sk->csum += checksum_mpi (sk->skey[4] );
1461 sk->csum += checksum_mpi (sk->skey[5] );
1462 if( ret_sk ) /* return an unprotected version of the sk */
1463 *ret_sk = copy_secret_key( NULL, sk );
1465 rc = genhelp_protect (dek, s2k, sk);
1466 if (rc)
1468 free_public_key (pk);
1469 free_secret_key (sk);
1470 return rc;
1473 pkt = xmalloc_clear(sizeof *pkt);
1474 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1475 pkt->pkt.public_key = pk;
1476 add_kbnode(pub_root, new_kbnode( pkt ));
1478 pkt = xmalloc_clear(sizeof *pkt);
1479 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1480 pkt->pkt.secret_key = sk;
1481 add_kbnode(sec_root, new_kbnode( pkt ));
1483 return 0;
1487 /****************
1488 * check valid days:
1489 * return 0 on error or the multiplier
1491 static int
1492 check_valid_days( const char *s )
1494 if( !digitp(s) )
1495 return 0;
1496 for( s++; *s; s++)
1497 if( !digitp(s) )
1498 break;
1499 if( !*s )
1500 return 1;
1501 if( s[1] )
1502 return 0; /* e.g. "2323wc" */
1503 if( *s == 'd' || *s == 'D' )
1504 return 1;
1505 if( *s == 'w' || *s == 'W' )
1506 return 7;
1507 if( *s == 'm' || *s == 'M' )
1508 return 30;
1509 if( *s == 'y' || *s == 'Y' )
1510 return 365;
1511 return 0;
1515 static void
1516 print_key_flags(int flags)
1518 if(flags&PUBKEY_USAGE_SIG)
1519 tty_printf("%s ",_("Sign"));
1521 if(flags&PUBKEY_USAGE_CERT)
1522 tty_printf("%s ",_("Certify"));
1524 if(flags&PUBKEY_USAGE_ENC)
1525 tty_printf("%s ",_("Encrypt"));
1527 if(flags&PUBKEY_USAGE_AUTH)
1528 tty_printf("%s ",_("Authenticate"));
1532 /* Returns the key flags */
1533 static unsigned int
1534 ask_key_flags(int algo,int subkey)
1536 /* TRANSLATORS: Please use only plain ASCII characters for the
1537 translation. If this is not possible use single digits. The
1538 string needs to 8 bytes long. Here is a description of the
1539 functions:
1541 s = Toggle signing capability
1542 e = Toggle encryption capability
1543 a = Toggle authentication capability
1544 q = Finish
1546 const char *togglers=_("SsEeAaQq");
1547 char *answer=NULL;
1548 unsigned int current=0;
1549 unsigned int possible=openpgp_pk_algo_usage(algo);
1551 if ( strlen(togglers) != 7 )
1553 tty_printf ("NOTE: Bad translation at %s:%d. "
1554 "Please report.\n", __FILE__, __LINE__);
1555 togglers = "11223300";
1558 /* Only primary keys may certify. */
1559 if(subkey)
1560 possible&=~PUBKEY_USAGE_CERT;
1562 /* Preload the current set with the possible set, minus
1563 authentication, since nobody really uses auth yet. */
1564 current=possible&~PUBKEY_USAGE_AUTH;
1566 for(;;)
1568 tty_printf("\n");
1569 tty_printf(_("Possible actions for a %s key: "),
1570 gcry_pk_algo_name (algo));
1571 print_key_flags(possible);
1572 tty_printf("\n");
1573 tty_printf(_("Current allowed actions: "));
1574 print_key_flags(current);
1575 tty_printf("\n\n");
1577 if(possible&PUBKEY_USAGE_SIG)
1578 tty_printf(_(" (%c) Toggle the sign capability\n"),
1579 togglers[0]);
1580 if(possible&PUBKEY_USAGE_ENC)
1581 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1582 togglers[2]);
1583 if(possible&PUBKEY_USAGE_AUTH)
1584 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1585 togglers[4]);
1587 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1588 tty_printf("\n");
1590 xfree(answer);
1591 answer = cpr_get("keygen.flags",_("Your selection? "));
1592 cpr_kill_prompt();
1594 if(strlen(answer)>1)
1595 tty_printf(_("Invalid selection.\n"));
1596 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1597 break;
1598 else if((*answer==togglers[0] || *answer==togglers[1])
1599 && possible&PUBKEY_USAGE_SIG)
1601 if(current&PUBKEY_USAGE_SIG)
1602 current&=~PUBKEY_USAGE_SIG;
1603 else
1604 current|=PUBKEY_USAGE_SIG;
1606 else if((*answer==togglers[2] || *answer==togglers[3])
1607 && possible&PUBKEY_USAGE_ENC)
1609 if(current&PUBKEY_USAGE_ENC)
1610 current&=~PUBKEY_USAGE_ENC;
1611 else
1612 current|=PUBKEY_USAGE_ENC;
1614 else if((*answer==togglers[4] || *answer==togglers[5])
1615 && possible&PUBKEY_USAGE_AUTH)
1617 if(current&PUBKEY_USAGE_AUTH)
1618 current&=~PUBKEY_USAGE_AUTH;
1619 else
1620 current|=PUBKEY_USAGE_AUTH;
1622 else
1623 tty_printf(_("Invalid selection.\n"));
1626 xfree(answer);
1628 return current;
1632 /****************
1633 * Returns: 0 to create both a DSA and a Elgamal key.
1634 * and only if key flags are to be written the desired usage.
1636 static int
1637 ask_algo (int addmode, unsigned int *r_usage)
1639 char *answer;
1640 int algo;
1642 *r_usage = 0;
1643 tty_printf(_("Please select what kind of key you want:\n"));
1644 if( !addmode )
1645 tty_printf(_(" (%d) DSA and Elgamal (default)\n"), 1 );
1646 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
1647 if (opt.expert)
1648 tty_printf( _(" (%d) DSA (set your own capabilities)\n"), 3 );
1649 if( addmode )
1650 tty_printf(_(" (%d) Elgamal (encrypt only)\n"), 4 );
1651 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
1652 if (addmode)
1653 tty_printf(_(" (%d) RSA (encrypt only)\n"), 6 );
1654 if (opt.expert)
1655 tty_printf( _(" (%d) RSA (set your own capabilities)\n"), 7 );
1657 for(;;) {
1658 answer = cpr_get("keygen.algo",_("Your selection? "));
1659 cpr_kill_prompt();
1660 algo = *answer? atoi(answer): 1;
1661 xfree(answer);
1662 if( algo == 1 && !addmode ) {
1663 algo = 0; /* create both keys */
1664 break;
1666 else if( algo == 7 && opt.expert ) {
1667 algo = PUBKEY_ALGO_RSA;
1668 *r_usage=ask_key_flags(algo,addmode);
1669 break;
1671 else if( algo == 6 && addmode ) {
1672 algo = PUBKEY_ALGO_RSA;
1673 *r_usage = PUBKEY_USAGE_ENC;
1674 break;
1676 else if( algo == 5 ) {
1677 algo = PUBKEY_ALGO_RSA;
1678 *r_usage = PUBKEY_USAGE_SIG;
1679 break;
1681 else if( algo == 4 && addmode ) {
1682 algo = PUBKEY_ALGO_ELGAMAL_E;
1683 *r_usage = PUBKEY_USAGE_ENC;
1684 break;
1686 else if( algo == 3 && opt.expert ) {
1687 algo = PUBKEY_ALGO_DSA;
1688 *r_usage=ask_key_flags(algo,addmode);
1689 break;
1691 else if( algo == 2 ) {
1692 algo = PUBKEY_ALGO_DSA;
1693 *r_usage = PUBKEY_USAGE_SIG;
1694 break;
1696 else
1697 tty_printf(_("Invalid selection.\n"));
1700 return algo;
1704 static unsigned
1705 ask_keysize( int algo )
1707 unsigned int nbits, min, def=2048, max=4096;
1709 if(opt.expert)
1710 min=512;
1711 else
1712 min=1024;
1714 switch(algo)
1716 case PUBKEY_ALGO_DSA:
1717 if(opt.flags.dsa2)
1719 def=1024;
1720 max=3072;
1722 else
1724 tty_printf(_("DSA keypair will have %u bits.\n"),1024);
1725 return 1024;
1727 break;
1729 case PUBKEY_ALGO_RSA:
1730 min=1024;
1731 break;
1734 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1735 gcry_pk_algo_name (algo), min, max);
1737 for(;;)
1739 char *prompt,*answer;
1741 #define PROMPTSTRING _("What keysize do you want? (%u) ")
1743 prompt=xmalloc(strlen(PROMPTSTRING)+20);
1744 sprintf(prompt,PROMPTSTRING,def);
1746 #undef PROMPTSTRING
1748 answer = cpr_get("keygen.size",prompt);
1749 cpr_kill_prompt();
1750 nbits = *answer? atoi(answer): def;
1751 xfree(prompt);
1752 xfree(answer);
1754 if(nbits<min || nbits>max)
1755 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1756 gcry_pk_algo_name (algo), min, max);
1757 else
1758 break;
1761 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1763 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
1765 nbits = ((nbits + 63) / 64) * 64;
1766 tty_printf(_("rounded up to %u bits\n"), nbits );
1768 else if( (nbits % 32) )
1770 nbits = ((nbits + 31) / 32) * 32;
1771 tty_printf(_("rounded up to %u bits\n"), nbits );
1774 return nbits;
1778 /****************
1779 * Parse an expire string and return its value in seconds.
1780 * Returns (u32)-1 on error.
1781 * This isn't perfect since scan_isodatestr returns unix time, and
1782 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1783 * Because of this, we only permit setting expirations up to 2106, but
1784 * OpenPGP could theoretically allow up to 2242. I think we'll all
1785 * just cope for the next few years until we get a 64-bit time_t or
1786 * similar.
1789 parse_expire_string( const char *string )
1791 int mult;
1792 u32 seconds,abs_date=0,curtime = make_timestamp();
1794 if( !*string )
1795 seconds = 0;
1796 else if ( !strncmp (string, "seconds=", 8) )
1797 seconds = atoi (string+8);
1798 else if( (abs_date = scan_isodatestr(string)) && abs_date > curtime )
1799 seconds = abs_date - curtime;
1800 else if( (mult=check_valid_days(string)) )
1801 seconds = atoi(string) * 86400L * mult;
1802 else
1803 seconds=(u32)-1;
1805 return seconds;
1808 /* Parsean Creation-Date string which is either "1986-04-26" or
1809 "19860426T042640". Returns 0 on error. */
1810 static u32
1811 parse_creation_string (const char *string)
1813 u32 seconds;
1815 if (!*string)
1816 seconds = 0;
1817 else if ( !strncmp (string, "seconds=", 8) )
1818 seconds = atoi (string+8);
1819 else if ( !(seconds = scan_isodatestr (string)))
1821 time_t tmp = isotime2epoch (string);
1822 seconds = (tmp == (time_t)(-1))? 0 : tmp;
1824 return seconds;
1828 /* object == 0 for a key, and 1 for a sig */
1830 ask_expire_interval(int object,const char *def_expire)
1832 u32 interval;
1833 char *answer;
1835 switch(object)
1837 case 0:
1838 if(def_expire)
1839 BUG();
1840 tty_printf(_("Please specify how long the key should be valid.\n"
1841 " 0 = key does not expire\n"
1842 " <n> = key expires in n days\n"
1843 " <n>w = key expires in n weeks\n"
1844 " <n>m = key expires in n months\n"
1845 " <n>y = key expires in n years\n"));
1846 break;
1848 case 1:
1849 if(!def_expire)
1850 BUG();
1851 tty_printf(_("Please specify how long the signature should be valid.\n"
1852 " 0 = signature does not expire\n"
1853 " <n> = signature expires in n days\n"
1854 " <n>w = signature expires in n weeks\n"
1855 " <n>m = signature expires in n months\n"
1856 " <n>y = signature expires in n years\n"));
1857 break;
1859 default:
1860 BUG();
1863 /* Note: The elgamal subkey for DSA has no expiration date because
1864 * it must be signed with the DSA key and this one has the expiration
1865 * date */
1867 answer = NULL;
1868 for(;;)
1870 u32 curtime=make_timestamp();
1872 xfree(answer);
1873 if(object==0)
1874 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1875 else
1877 char *prompt;
1879 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1880 /* This will actually end up larger than necessary because
1881 of the 2 bytes for '%s' */
1882 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
1883 sprintf(prompt,PROMPTSTRING,def_expire);
1884 #undef PROMPTSTRING
1886 answer = cpr_get("siggen.valid",prompt);
1887 xfree(prompt);
1889 if(*answer=='\0')
1890 answer=xstrdup(def_expire);
1892 cpr_kill_prompt();
1893 trim_spaces(answer);
1894 interval = parse_expire_string( answer );
1895 if( interval == (u32)-1 )
1897 tty_printf(_("invalid value\n"));
1898 continue;
1901 if( !interval )
1903 tty_printf((object==0)
1904 ? _("Key does not expire at all\n")
1905 : _("Signature does not expire at all\n"));
1907 else
1909 tty_printf(object==0
1910 ? _("Key expires at %s\n")
1911 : _("Signature expires at %s\n"),
1912 asctimestamp((ulong)(curtime + interval) ) );
1913 #if SIZEOF_TIME_T <= 4
1914 if ( (time_t)((ulong)(curtime+interval)) < 0 )
1915 tty_printf (_("Your system can't display dates beyond 2038.\n"
1916 "However, it will be correctly handled up to"
1917 " 2106.\n"));
1918 #endif /*SIZEOF_TIME_T*/
1921 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1922 _("Is this correct? (y/N) ")) )
1923 break;
1926 xfree(answer);
1927 return interval;
1931 ask_expiredate()
1933 u32 x = ask_expire_interval(0,NULL);
1934 return x? make_timestamp() + x : 0;
1938 static char *
1939 ask_user_id( int mode )
1941 char *answer;
1942 char *aname, *acomment, *amail, *uid;
1944 if( !mode )
1945 tty_printf( _("\n"
1946 "You need a user ID to identify your key; "
1947 "the software constructs the user ID\n"
1948 "from the Real Name, Comment and Email Address in this form:\n"
1949 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n") );
1950 uid = aname = acomment = amail = NULL;
1951 for(;;) {
1952 char *p;
1953 int fail=0;
1955 if( !aname ) {
1956 for(;;) {
1957 xfree(aname);
1958 aname = cpr_get("keygen.name",_("Real name: "));
1959 trim_spaces(aname);
1960 cpr_kill_prompt();
1962 if( opt.allow_freeform_uid )
1963 break;
1965 if( strpbrk( aname, "<>" ) )
1966 tty_printf(_("Invalid character in name\n"));
1967 else if( digitp(aname) )
1968 tty_printf(_("Name may not start with a digit\n"));
1969 else if( strlen(aname) < 5 )
1970 tty_printf(_("Name must be at least 5 characters long\n"));
1971 else
1972 break;
1975 if( !amail ) {
1976 for(;;) {
1977 xfree(amail);
1978 amail = cpr_get("keygen.email",_("Email address: "));
1979 trim_spaces(amail);
1980 cpr_kill_prompt();
1981 if( !*amail || opt.allow_freeform_uid )
1982 break; /* no email address is okay */
1983 else if ( !is_valid_mailbox (amail) )
1984 tty_printf(_("Not a valid email address\n"));
1985 else
1986 break;
1989 if( !acomment ) {
1990 for(;;) {
1991 xfree(acomment);
1992 acomment = cpr_get("keygen.comment",_("Comment: "));
1993 trim_spaces(acomment);
1994 cpr_kill_prompt();
1995 if( !*acomment )
1996 break; /* no comment is okay */
1997 else if( strpbrk( acomment, "()" ) )
1998 tty_printf(_("Invalid character in comment\n"));
1999 else
2000 break;
2005 xfree(uid);
2006 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2007 p = stpcpy(p, aname );
2008 if( *acomment )
2009 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2010 if( *amail )
2011 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2013 /* Append a warning if the RNG is switched into fake mode. */
2014 if ( random_is_faked () )
2015 strcpy(p, " (insecure!)" );
2017 /* print a note in case that UTF8 mapping has to be done */
2018 for(p=uid; *p; p++ ) {
2019 if( *p & 0x80 ) {
2020 tty_printf(_("You are using the `%s' character set.\n"),
2021 get_native_charset() );
2022 break;
2026 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2027 /* fixme: add a warning if this user-id already exists */
2028 if( !*amail && !opt.allow_freeform_uid
2029 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2030 fail = 1;
2031 tty_printf(_("Please don't put the email address "
2032 "into the real name or the comment\n") );
2035 for(;;) {
2036 /* TRANSLATORS: These are the allowed answers in
2037 lower and uppercase. Below you will find the matching
2038 string which should be translated accordingly and the
2039 letter changed to match the one in the answer string.
2041 n = Change name
2042 c = Change comment
2043 e = Change email
2044 o = Okay (ready, continue)
2045 q = Quit
2047 const char *ansstr = _("NnCcEeOoQq");
2049 if( strlen(ansstr) != 10 )
2050 BUG();
2051 if( cpr_enabled() ) {
2052 answer = xstrdup(ansstr+6);
2053 answer[1] = 0;
2055 else {
2056 answer = cpr_get("keygen.userid.cmd", fail?
2057 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2058 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2059 cpr_kill_prompt();
2061 if( strlen(answer) > 1 )
2063 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2064 xfree(aname); aname = NULL;
2065 break;
2067 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2068 xfree(acomment); acomment = NULL;
2069 break;
2071 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2072 xfree(amail); amail = NULL;
2073 break;
2075 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2076 if( fail ) {
2077 tty_printf(_("Please correct the error first\n"));
2079 else {
2080 xfree(aname); aname = NULL;
2081 xfree(acomment); acomment = NULL;
2082 xfree(amail); amail = NULL;
2083 break;
2086 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2087 xfree(aname); aname = NULL;
2088 xfree(acomment); acomment = NULL;
2089 xfree(amail); amail = NULL;
2090 xfree(uid); uid = NULL;
2091 break;
2093 xfree(answer);
2095 xfree(answer);
2096 if( !amail && !acomment && !amail )
2097 break;
2098 xfree(uid); uid = NULL;
2100 if( uid ) {
2101 char *p = native_to_utf8( uid );
2102 xfree( uid );
2103 uid = p;
2105 return uid;
2109 static DEK *
2110 do_ask_passphrase ( STRING2KEY **ret_s2k, int *r_canceled )
2112 DEK *dek = NULL;
2113 STRING2KEY *s2k;
2114 const char *errtext = NULL;
2116 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2118 s2k = xmalloc_secure( sizeof *s2k );
2119 for(;;) {
2120 s2k->mode = opt.s2k_mode;
2121 s2k->hash_algo = S2K_DIGEST_ALGO;
2122 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k,2,
2123 errtext, r_canceled);
2124 if (!dek && *r_canceled) {
2125 xfree(dek); dek = NULL;
2126 xfree(s2k); s2k = NULL;
2127 break;
2129 else if( !dek ) {
2130 errtext = N_("passphrase not correctly repeated; try again");
2131 tty_printf(_("%s.\n"), _(errtext));
2133 else if( !dek->keylen ) {
2134 xfree(dek); dek = NULL;
2135 xfree(s2k); s2k = NULL;
2136 tty_printf(_(
2137 "You don't want a passphrase - this is probably a *bad* idea!\n"
2138 "I will do it anyway. You can change your passphrase at any time,\n"
2139 "using this program with the option \"--edit-key\".\n\n"));
2140 break;
2142 else
2143 break; /* okay */
2145 *ret_s2k = s2k;
2146 return dek;
2150 /* Basic key generation. Here we divert to the actual generation
2151 routines based on the requested algorithm. */
2152 static int
2153 do_create (int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
2154 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk,
2155 u32 timestamp, u32 expiredate, int is_subkey )
2157 int rc=0;
2159 if( !opt.batch )
2160 tty_printf(_(
2161 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2162 "some other action (type on the keyboard, move the mouse, utilize the\n"
2163 "disks) during the prime generation; this gives the random number\n"
2164 "generator a better chance to gain enough entropy.\n") );
2166 if( algo == PUBKEY_ALGO_ELGAMAL_E )
2167 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2168 timestamp, expiredate, is_subkey);
2169 else if( algo == PUBKEY_ALGO_DSA )
2170 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk,
2171 timestamp, expiredate, is_subkey);
2172 else if( algo == PUBKEY_ALGO_RSA )
2173 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2174 timestamp, expiredate, is_subkey);
2175 else
2176 BUG();
2178 return rc;
2182 /****************
2183 * Generate a new user id packet, or return NULL if canceled
2185 PKT_user_id *
2186 generate_user_id()
2188 PKT_user_id *uid;
2189 char *p;
2190 size_t n;
2192 p = ask_user_id( 1 );
2193 if( !p )
2194 return NULL;
2195 n = strlen(p);
2196 uid = xmalloc_clear( sizeof *uid + n );
2197 uid->len = n;
2198 strcpy(uid->name, p);
2199 uid->ref = 1;
2200 return uid;
2204 static void
2205 release_parameter_list( struct para_data_s *r )
2207 struct para_data_s *r2;
2209 for( ; r ; r = r2 ) {
2210 r2 = r->next;
2211 if( r->key == pPASSPHRASE_DEK )
2212 xfree( r->u.dek );
2213 else if( r->key == pPASSPHRASE_S2K )
2214 xfree( r->u.s2k );
2216 xfree(r);
2220 static struct para_data_s *
2221 get_parameter( struct para_data_s *para, enum para_name key )
2223 struct para_data_s *r;
2225 for( r = para; r && r->key != key; r = r->next )
2227 return r;
2230 static const char *
2231 get_parameter_value( struct para_data_s *para, enum para_name key )
2233 struct para_data_s *r = get_parameter( para, key );
2234 return (r && *r->u.value)? r->u.value : NULL;
2237 static int
2238 get_parameter_algo( struct para_data_s *para, enum para_name key )
2240 int i;
2241 struct para_data_s *r = get_parameter( para, key );
2242 if( !r )
2243 return -1;
2244 if( digitp( r->u.value ) )
2245 i = atoi( r->u.value );
2246 else if ( !strcmp ( r->u.value, "ELG-E")
2247 || !strcmp ( r->u.value, "ELG") )
2248 i = GCRY_PK_ELG_E;
2249 else
2250 i = gcry_pk_map_name (r->u.value);
2251 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2252 i = 0; /* we don't want to allow generation of these algorithms */
2253 return i;
2257 * parse the usage parameter and set the keyflags. Return true on error.
2259 static int
2260 parse_parameter_usage (const char *fname,
2261 struct para_data_s *para, enum para_name key)
2263 struct para_data_s *r = get_parameter( para, key );
2264 char *p, *pn;
2265 unsigned int use;
2267 if( !r )
2268 return 0; /* none (this is an optional parameter)*/
2270 use = 0;
2271 pn = r->u.value;
2272 while ( (p = strsep (&pn, " \t,")) ) {
2273 if ( !*p)
2275 else if ( !ascii_strcasecmp (p, "sign") )
2276 use |= PUBKEY_USAGE_SIG;
2277 else if ( !ascii_strcasecmp (p, "encrypt") )
2278 use |= PUBKEY_USAGE_ENC;
2279 else if ( !ascii_strcasecmp (p, "auth") )
2280 use |= PUBKEY_USAGE_AUTH;
2281 else {
2282 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2283 return -1; /* error */
2286 r->u.usage = use;
2287 return 1;
2290 static int
2291 parse_revocation_key (const char *fname,
2292 struct para_data_s *para, enum para_name key)
2294 struct para_data_s *r = get_parameter( para, key );
2295 struct revocation_key revkey;
2296 char *pn;
2297 int i;
2299 if( !r )
2300 return 0; /* none (this is an optional parameter) */
2302 pn = r->u.value;
2304 revkey.class=0x80;
2305 revkey.algid=atoi(pn);
2306 if(!revkey.algid)
2307 goto fail;
2309 /* Skip to the fpr */
2310 while(*pn && *pn!=':')
2311 pn++;
2313 if(*pn!=':')
2314 goto fail;
2316 pn++;
2318 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2320 int c=hextobyte(pn);
2321 if(c==-1)
2322 goto fail;
2324 revkey.fpr[i]=c;
2327 /* skip to the tag */
2328 while(*pn && *pn!='s' && *pn!='S')
2329 pn++;
2331 if(ascii_strcasecmp(pn,"sensitive")==0)
2332 revkey.class|=0x40;
2334 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2336 return 0;
2338 fail:
2339 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2340 return -1; /* error */
2344 static u32
2345 get_parameter_u32( struct para_data_s *para, enum para_name key )
2347 struct para_data_s *r = get_parameter( para, key );
2349 if( !r )
2350 return 0;
2351 if( r->key == pKEYCREATIONDATE )
2352 return r->u.creation;
2353 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2354 return r->u.expire;
2355 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2356 return r->u.usage;
2358 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2361 static unsigned int
2362 get_parameter_uint( struct para_data_s *para, enum para_name key )
2364 return get_parameter_u32( para, key );
2367 static DEK *
2368 get_parameter_dek( struct para_data_s *para, enum para_name key )
2370 struct para_data_s *r = get_parameter( para, key );
2371 return r? r->u.dek : NULL;
2374 static STRING2KEY *
2375 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2377 struct para_data_s *r = get_parameter( para, key );
2378 return r? r->u.s2k : NULL;
2381 static struct revocation_key *
2382 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2384 struct para_data_s *r = get_parameter( para, key );
2385 return r? &r->u.revkey : NULL;
2388 static int
2389 proc_parameter_file( struct para_data_s *para, const char *fname,
2390 struct output_control_s *outctrl, int card )
2392 struct para_data_s *r;
2393 const char *s1, *s2, *s3;
2394 size_t n;
2395 char *p;
2396 int have_user_id=0,err,algo;
2398 /* Check that we have all required parameters. */
2399 r = get_parameter( para, pKEYTYPE );
2400 if(r)
2402 algo=get_parameter_algo(para,pKEYTYPE);
2403 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2405 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
2406 return -1;
2409 else
2411 log_error("%s: no Key-Type specified\n",fname);
2412 return -1;
2415 err=parse_parameter_usage (fname, para, pKEYUSAGE);
2416 if(err==0)
2418 /* Default to algo capabilities if key-usage is not provided */
2419 r=xmalloc_clear(sizeof(*r));
2420 r->key=pKEYUSAGE;
2421 r->u.usage=openpgp_pk_algo_usage(algo);
2422 r->next=para;
2423 para=r;
2425 else if(err==-1)
2426 return -1;
2428 r = get_parameter( para, pSUBKEYTYPE );
2429 if(r)
2431 algo=get_parameter_algo( para, pSUBKEYTYPE);
2432 if (openpgp_pk_test_algo (algo))
2434 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
2435 return -1;
2438 err=parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2439 if(err==0)
2441 /* Default to algo capabilities if subkey-usage is not
2442 provided */
2443 r=xmalloc_clear(sizeof(*r));
2444 r->key=pSUBKEYUSAGE;
2445 r->u.usage=openpgp_pk_algo_usage(algo);
2446 r->next=para;
2447 para=r;
2449 else if(err==-1)
2450 return -1;
2453 if( get_parameter_value( para, pUSERID ) )
2454 have_user_id=1;
2455 else
2457 /* create the formatted user ID */
2458 s1 = get_parameter_value( para, pNAMEREAL );
2459 s2 = get_parameter_value( para, pNAMECOMMENT );
2460 s3 = get_parameter_value( para, pNAMEEMAIL );
2461 if( s1 || s2 || s3 )
2463 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2464 r = xmalloc_clear( sizeof *r + n + 20 );
2465 r->key = pUSERID;
2466 p = r->u.value;
2467 if( s1 )
2468 p = stpcpy(p, s1 );
2469 if( s2 )
2470 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2471 if( s3 )
2472 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2473 r->next = para;
2474 para = r;
2475 have_user_id=1;
2479 if(!have_user_id)
2481 log_error("%s: no User-ID specified\n",fname);
2482 return -1;
2485 /* Set preferences, if any. */
2486 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2488 /* Set keyserver, if any. */
2489 s1=get_parameter_value( para, pKEYSERVER );
2490 if(s1)
2492 struct keyserver_spec *spec;
2494 spec=parse_keyserver_uri(s1,1,NULL,0);
2495 if(spec)
2497 free_keyserver_spec(spec);
2498 opt.def_keyserver_url=s1;
2500 else
2502 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2503 return -1;
2507 /* Set revoker, if any. */
2508 if (parse_revocation_key (fname, para, pREVOKER))
2509 return -1;
2511 /* make DEK and S2K from the Passphrase */
2512 r = get_parameter( para, pPASSPHRASE );
2513 if( r && *r->u.value ) {
2514 /* We have a plain text passphrase - create a DEK from it.
2515 * It is a little bit ridiculous to keep it ih secure memory
2516 * but because we do this always, why not here */
2517 STRING2KEY *s2k;
2518 DEK *dek;
2520 s2k = xmalloc_secure( sizeof *s2k );
2521 s2k->mode = opt.s2k_mode;
2522 s2k->hash_algo = S2K_DIGEST_ALGO;
2523 set_next_passphrase( r->u.value );
2524 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2525 NULL, NULL);
2526 set_next_passphrase( NULL );
2527 assert( dek );
2528 memset( r->u.value, 0, strlen(r->u.value) );
2530 r = xmalloc_clear( sizeof *r );
2531 r->key = pPASSPHRASE_S2K;
2532 r->u.s2k = s2k;
2533 r->next = para;
2534 para = r;
2535 r = xmalloc_clear( sizeof *r );
2536 r->key = pPASSPHRASE_DEK;
2537 r->u.dek = dek;
2538 r->next = para;
2539 para = r;
2542 /* Make KEYCREATIONDATE from Creation-Date. */
2543 r = get_parameter (para, pCREATIONDATE);
2544 if (r && *r->u.value)
2546 u32 seconds;
2548 seconds = parse_creation_string (r->u.value);
2549 if (!seconds)
2551 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2552 return -1;
2554 r->u.creation = seconds;
2555 r->key = pKEYCREATIONDATE; /* Change that entry. */
2558 /* Make KEYEXPIRE from Expire-Date. */
2559 r = get_parameter( para, pEXPIREDATE );
2560 if( r && *r->u.value )
2562 u32 seconds;
2564 seconds = parse_expire_string( r->u.value );
2565 if( seconds == (u32)-1 )
2567 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2568 return -1;
2570 r->u.expire = seconds;
2571 r->key = pKEYEXPIRE; /* change hat entry */
2572 /* also set it for the subkey */
2573 r = xmalloc_clear( sizeof *r + 20 );
2574 r->key = pSUBKEYEXPIRE;
2575 r->u.expire = seconds;
2576 r->next = para;
2577 para = r;
2580 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2581 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2582 return -1;
2585 do_generate_keypair( para, outctrl, card );
2586 return 0;
2590 /****************
2591 * Kludge to allow non interactive key generation controlled
2592 * by a parameter file.
2593 * Note, that string parameters are expected to be in UTF-8
2595 static void
2596 read_parameter_file( const char *fname )
2598 static struct { const char *name;
2599 enum para_name key;
2600 } keywords[] = {
2601 { "Key-Type", pKEYTYPE},
2602 { "Key-Length", pKEYLENGTH },
2603 { "Key-Usage", pKEYUSAGE },
2604 { "Subkey-Type", pSUBKEYTYPE },
2605 { "Subkey-Length", pSUBKEYLENGTH },
2606 { "Subkey-Usage", pSUBKEYUSAGE },
2607 { "Name-Real", pNAMEREAL },
2608 { "Name-Email", pNAMEEMAIL },
2609 { "Name-Comment", pNAMECOMMENT },
2610 { "Expire-Date", pEXPIREDATE },
2611 { "Creation-Date", pCREATIONDATE },
2612 { "Passphrase", pPASSPHRASE },
2613 { "Preferences", pPREFERENCES },
2614 { "Revoker", pREVOKER },
2615 { "Handle", pHANDLE },
2616 { "Keyserver", pKEYSERVER },
2617 { NULL, 0 }
2619 IOBUF fp;
2620 byte *line;
2621 unsigned int maxlen, nline;
2622 char *p;
2623 int lnr;
2624 const char *err = NULL;
2625 struct para_data_s *para, *r;
2626 int i;
2627 struct output_control_s outctrl;
2629 memset( &outctrl, 0, sizeof( outctrl ) );
2630 outctrl.pub.afx = new_armor_context ();
2631 outctrl.sec.afx = new_armor_context ();
2633 if( !fname || !*fname)
2634 fname = "-";
2636 fp = iobuf_open (fname);
2637 if (fp && is_secured_file (iobuf_get_fd (fp)))
2639 iobuf_close (fp);
2640 fp = NULL;
2641 errno = EPERM;
2643 if (!fp) {
2644 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2645 return;
2647 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2649 lnr = 0;
2650 err = NULL;
2651 para = NULL;
2652 maxlen = 1024;
2653 line = NULL;
2654 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2655 char *keyword, *value;
2657 lnr++;
2658 if( !maxlen ) {
2659 err = "line too long";
2660 break;
2662 for( p = line; isspace(*(byte*)p); p++ )
2664 if( !*p || *p == '#' )
2665 continue;
2666 keyword = p;
2667 if( *keyword == '%' ) {
2668 for( ; !isspace(*(byte*)p); p++ )
2670 if( *p )
2671 *p++ = 0;
2672 for( ; isspace(*(byte*)p); p++ )
2674 value = p;
2675 trim_trailing_ws( value, strlen(value) );
2676 if( !ascii_strcasecmp( keyword, "%echo" ) )
2677 log_info("%s\n", value );
2678 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2679 outctrl.dryrun = 1;
2680 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2681 outctrl.lnr = lnr;
2682 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2683 print_status_key_not_created
2684 (get_parameter_value (para, pHANDLE));
2685 release_parameter_list( para );
2686 para = NULL;
2688 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2689 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2690 ; /* still the same file - ignore it */
2691 else {
2692 xfree( outctrl.pub.newfname );
2693 outctrl.pub.newfname = xstrdup( value );
2694 outctrl.use_files = 1;
2697 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2698 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2699 ; /* still the same file - ignore it */
2700 else {
2701 xfree( outctrl.sec.newfname );
2702 outctrl.sec.newfname = xstrdup( value );
2703 outctrl.use_files = 1;
2706 else
2707 log_info("skipping control `%s' (%s)\n", keyword, value );
2710 continue;
2714 if( !(p = strchr( p, ':' )) || p == keyword ) {
2715 err = "missing colon";
2716 break;
2718 if( *p )
2719 *p++ = 0;
2720 for( ; isspace(*(byte*)p); p++ )
2722 if( !*p ) {
2723 err = "missing argument";
2724 break;
2726 value = p;
2727 trim_trailing_ws( value, strlen(value) );
2729 for(i=0; keywords[i].name; i++ ) {
2730 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2731 break;
2733 if( !keywords[i].name ) {
2734 err = "unknown keyword";
2735 break;
2737 if( keywords[i].key != pKEYTYPE && !para ) {
2738 err = "parameter block does not start with \"Key-Type\"";
2739 break;
2742 if( keywords[i].key == pKEYTYPE && para ) {
2743 outctrl.lnr = lnr;
2744 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2745 print_status_key_not_created
2746 (get_parameter_value (para, pHANDLE));
2747 release_parameter_list( para );
2748 para = NULL;
2750 else {
2751 for( r = para; r; r = r->next ) {
2752 if( r->key == keywords[i].key )
2753 break;
2755 if( r ) {
2756 err = "duplicate keyword";
2757 break;
2760 r = xmalloc_clear( sizeof *r + strlen( value ) );
2761 r->lnr = lnr;
2762 r->key = keywords[i].key;
2763 strcpy( r->u.value, value );
2764 r->next = para;
2765 para = r;
2767 if( err )
2768 log_error("%s:%d: %s\n", fname, lnr, err );
2769 else if( iobuf_error (fp) ) {
2770 log_error("%s:%d: read error\n", fname, lnr);
2772 else if( para ) {
2773 outctrl.lnr = lnr;
2774 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2775 print_status_key_not_created (get_parameter_value (para, pHANDLE));
2778 if( outctrl.use_files ) { /* close open streams */
2779 iobuf_close( outctrl.pub.stream );
2780 iobuf_close( outctrl.sec.stream );
2782 /* Must invalidate that ugly cache to actually close it. */
2783 if (outctrl.pub.fname)
2784 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
2785 if (outctrl.sec.fname)
2786 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
2788 xfree( outctrl.pub.fname );
2789 xfree( outctrl.pub.newfname );
2790 xfree( outctrl.sec.fname );
2791 xfree( outctrl.sec.newfname );
2794 release_parameter_list( para );
2795 iobuf_close (fp);
2796 release_armor_context (outctrl.pub.afx);
2797 release_armor_context (outctrl.sec.afx);
2802 * Generate a keypair (fname is only used in batch mode) If
2803 * CARD_SERIALNO is not NULL the function will create the keys on an
2804 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2805 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2806 * generate in software, imported to the card and a backup file
2807 * written to directory given by this argument .
2809 void
2810 generate_keypair (const char *fname, const char *card_serialno,
2811 const char *backup_encryption_dir)
2813 unsigned int nbits;
2814 char *uid = NULL;
2815 DEK *dek;
2816 STRING2KEY *s2k;
2817 int algo;
2818 unsigned int use;
2819 int both = 0;
2820 u32 expire;
2821 struct para_data_s *para = NULL;
2822 struct para_data_s *r;
2823 struct output_control_s outctrl;
2824 int canceled;
2826 memset( &outctrl, 0, sizeof( outctrl ) );
2828 if (opt.batch && card_serialno)
2830 /* We don't yet support unattended key generation. */
2831 log_error (_("can't do this in batch mode\n"));
2832 return;
2835 if (opt.batch)
2837 read_parameter_file( fname );
2838 return;
2841 if (card_serialno)
2843 #ifdef ENABLE_CARD_SUPPORT
2844 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
2845 r->key = pSERIALNO;
2846 strcpy( r->u.value, card_serialno);
2847 r->next = para;
2848 para = r;
2850 algo = PUBKEY_ALGO_RSA;
2852 r = xcalloc (1, sizeof *r + 20 );
2853 r->key = pKEYTYPE;
2854 sprintf( r->u.value, "%d", algo );
2855 r->next = para;
2856 para = r;
2857 r = xcalloc (1, sizeof *r + 20 );
2858 r->key = pKEYUSAGE;
2859 strcpy (r->u.value, "sign");
2860 r->next = para;
2861 para = r;
2863 r = xcalloc (1, sizeof *r + 20 );
2864 r->key = pSUBKEYTYPE;
2865 sprintf( r->u.value, "%d", algo );
2866 r->next = para;
2867 para = r;
2868 r = xcalloc (1, sizeof *r + 20 );
2869 r->key = pSUBKEYUSAGE;
2870 strcpy (r->u.value, "encrypt");
2871 r->next = para;
2872 para = r;
2874 r = xcalloc (1, sizeof *r + 20 );
2875 r->key = pAUTHKEYTYPE;
2876 sprintf( r->u.value, "%d", algo );
2877 r->next = para;
2878 para = r;
2880 if (backup_encryption_dir)
2882 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
2883 r->key = pBACKUPENCDIR;
2884 strcpy (r->u.value, backup_encryption_dir);
2885 r->next = para;
2886 para = r;
2888 #endif /*ENABLE_CARD_SUPPORT*/
2890 else
2892 algo = ask_algo( 0, &use );
2893 if( !algo )
2894 { /* default: DSA with ElG subkey of the specified size */
2895 both = 1;
2896 r = xmalloc_clear( sizeof *r + 20 );
2897 r->key = pKEYTYPE;
2898 sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
2899 r->next = para;
2900 para = r;
2901 nbits = ask_keysize( PUBKEY_ALGO_DSA );
2902 r = xmalloc_clear( sizeof *r + 20 );
2903 r->key = pKEYLENGTH;
2904 sprintf( r->u.value, "%u", nbits);
2905 r->next = para;
2906 para = r;
2907 r = xmalloc_clear( sizeof *r + 20 );
2908 r->key = pKEYUSAGE;
2909 strcpy( r->u.value, "sign" );
2910 r->next = para;
2911 para = r;
2913 algo = PUBKEY_ALGO_ELGAMAL_E;
2914 r = xmalloc_clear( sizeof *r + 20 );
2915 r->key = pSUBKEYTYPE;
2916 sprintf( r->u.value, "%d", algo );
2917 r->next = para;
2918 para = r;
2919 r = xmalloc_clear( sizeof *r + 20 );
2920 r->key = pSUBKEYUSAGE;
2921 strcpy( r->u.value, "encrypt" );
2922 r->next = para;
2923 para = r;
2925 else
2927 r = xmalloc_clear( sizeof *r + 20 );
2928 r->key = pKEYTYPE;
2929 sprintf( r->u.value, "%d", algo );
2930 r->next = para;
2931 para = r;
2933 if (use)
2935 r = xmalloc_clear( sizeof *r + 25 );
2936 r->key = pKEYUSAGE;
2937 sprintf( r->u.value, "%s%s%s",
2938 (use & PUBKEY_USAGE_SIG)? "sign ":"",
2939 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
2940 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
2941 r->next = para;
2942 para = r;
2947 nbits = ask_keysize( algo );
2948 r = xmalloc_clear( sizeof *r + 20 );
2949 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
2950 sprintf( r->u.value, "%u", nbits);
2951 r->next = para;
2952 para = r;
2955 expire = ask_expire_interval(0,NULL);
2956 r = xmalloc_clear( sizeof *r + 20 );
2957 r->key = pKEYEXPIRE;
2958 r->u.expire = expire;
2959 r->next = para;
2960 para = r;
2961 r = xmalloc_clear( sizeof *r + 20 );
2962 r->key = pSUBKEYEXPIRE;
2963 r->u.expire = expire;
2964 r->next = para;
2965 para = r;
2967 uid = ask_user_id(0);
2968 if( !uid )
2970 log_error(_("Key generation canceled.\n"));
2971 release_parameter_list( para );
2972 return;
2974 r = xmalloc_clear( sizeof *r + strlen(uid) );
2975 r->key = pUSERID;
2976 strcpy( r->u.value, uid );
2977 r->next = para;
2978 para = r;
2980 canceled = 0;
2981 dek = card_serialno? NULL : do_ask_passphrase ( &s2k, &canceled );
2982 if( dek )
2984 r = xmalloc_clear( sizeof *r );
2985 r->key = pPASSPHRASE_DEK;
2986 r->u.dek = dek;
2987 r->next = para;
2988 para = r;
2989 r = xmalloc_clear( sizeof *r );
2990 r->key = pPASSPHRASE_S2K;
2991 r->u.s2k = s2k;
2992 r->next = para;
2993 para = r;
2996 if (canceled)
2997 log_error (_("Key generation canceled.\n"));
2998 else
2999 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3000 release_parameter_list( para );
3004 #ifdef ENABLE_CARD_SUPPORT
3005 /* Generate a raw key and return it as a secret key packet. The
3006 function will ask for the passphrase and return a protected as well
3007 as an unprotected copy of a new secret key packet. 0 is returned
3008 on success and the caller must then free the returned values. */
3009 static int
3010 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3011 PKT_secret_key **r_sk_unprotected,
3012 PKT_secret_key **r_sk_protected)
3014 int rc;
3015 DEK *dek = NULL;
3016 STRING2KEY *s2k = NULL;
3017 PKT_secret_key *sk = NULL;
3018 int i;
3019 size_t nskey, npkey;
3020 gcry_sexp_t s_parms, s_key;
3021 int canceled;
3023 npkey = pubkey_get_npkey (algo);
3024 nskey = pubkey_get_nskey (algo);
3025 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3027 if (nbits < 512)
3029 nbits = 512;
3030 log_info (_("keysize invalid; using %u bits\n"), nbits );
3033 if ((nbits % 32))
3035 nbits = ((nbits + 31) / 32) * 32;
3036 log_info(_("keysize rounded up to %u bits\n"), nbits );
3039 dek = do_ask_passphrase (&s2k, &canceled);
3040 if (canceled)
3042 rc = gpg_error (GPG_ERR_CANCELED);
3043 goto leave;
3046 sk = xmalloc_clear (sizeof *sk);
3047 sk->timestamp = created_at;
3048 sk->version = 4;
3049 sk->pubkey_algo = algo;
3051 if ( !is_RSA (algo) )
3053 log_error ("only RSA is supported for offline generated keys\n");
3054 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3055 goto leave;
3057 rc = gcry_sexp_build (&s_parms, NULL,
3058 "(genkey(rsa(nbits %d)))",
3059 (int)nbits);
3060 if (rc)
3061 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3062 rc = gcry_pk_genkey (&s_key, s_parms);
3063 gcry_sexp_release (s_parms);
3064 if (rc)
3066 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3067 goto leave;
3069 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3070 gcry_sexp_release (s_key);
3071 if (rc)
3073 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3074 goto leave;
3077 for (i=npkey; i < nskey; i++)
3078 sk->csum += checksum_mpi (sk->skey[i]);
3080 if (r_sk_unprotected)
3081 *r_sk_unprotected = copy_secret_key (NULL, sk);
3083 rc = genhelp_protect (dek, s2k, sk);
3084 if (rc)
3085 goto leave;
3087 if (r_sk_protected)
3089 *r_sk_protected = sk;
3090 sk = NULL;
3093 leave:
3094 if (sk)
3095 free_secret_key (sk);
3096 xfree (dek);
3097 xfree (s2k);
3098 return rc;
3100 #endif /* ENABLE_CARD_SUPPORT */
3102 /* Create and delete a dummy packet to start off a list of kbnodes. */
3103 static void
3104 start_tree(KBNODE *tree)
3106 PACKET *pkt;
3108 pkt=xmalloc_clear(sizeof(*pkt));
3109 pkt->pkttype=PKT_NONE;
3110 *tree=new_kbnode(pkt);
3111 delete_kbnode(*tree);
3115 static void
3116 do_generate_keypair (struct para_data_s *para,
3117 struct output_control_s *outctrl, int card)
3119 KBNODE pub_root = NULL;
3120 KBNODE sec_root = NULL;
3121 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3122 const char *s;
3123 struct revocation_key *revkey;
3124 int rc;
3125 int did_sub = 0;
3126 u32 timestamp;
3128 if( outctrl->dryrun )
3130 log_info("dry-run mode - key generation skipped\n");
3131 return;
3134 if ( outctrl->use_files )
3136 if ( outctrl->pub.newfname )
3138 iobuf_close(outctrl->pub.stream);
3139 outctrl->pub.stream = NULL;
3140 if (outctrl->pub.fname)
3141 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3142 xfree( outctrl->pub.fname );
3143 outctrl->pub.fname = outctrl->pub.newfname;
3144 outctrl->pub.newfname = NULL;
3146 if (is_secured_filename (outctrl->pub.fname) )
3148 outctrl->pub.stream = NULL;
3149 errno = EPERM;
3151 else
3152 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3153 if (!outctrl->pub.stream)
3155 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3156 strerror(errno) );
3157 return;
3159 if (opt.armor)
3161 outctrl->pub.afx->what = 1;
3162 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3165 if (outctrl->sec.newfname)
3167 mode_t oldmask;
3169 iobuf_close(outctrl->sec.stream);
3170 outctrl->sec.stream = NULL;
3171 if (outctrl->sec.fname)
3172 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3173 xfree( outctrl->sec.fname );
3174 outctrl->sec.fname = outctrl->sec.newfname;
3175 outctrl->sec.newfname = NULL;
3177 oldmask = umask (077);
3178 if (is_secured_filename (outctrl->sec.fname) )
3180 outctrl->sec.stream = NULL;
3181 errno = EPERM;
3183 else
3184 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3185 umask (oldmask);
3186 if (!outctrl->sec.stream)
3188 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3189 strerror(errno) );
3190 return;
3192 if (opt.armor)
3194 outctrl->sec.afx->what = 5;
3195 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3198 assert( outctrl->pub.stream );
3199 assert( outctrl->sec.stream );
3200 if (opt.verbose)
3202 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3203 if (card)
3204 log_info (_("writing secret key stub to `%s'\n"),
3205 outctrl->sec.fname);
3206 else
3207 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3212 /* We create the packets as a tree of kbnodes. Because the
3213 structure we create is known in advance we simply generate a
3214 linked list. The first packet is a dummy packet which we flag as
3215 deleted. The very first packet must always be a KEY packet. */
3217 start_tree (&pub_root);
3218 start_tree (&sec_root);
3220 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3221 if (!timestamp)
3222 timestamp = make_timestamp ();
3224 if (!card)
3226 rc = do_create (get_parameter_algo( para, pKEYTYPE ),
3227 get_parameter_uint( para, pKEYLENGTH ),
3228 pub_root, sec_root,
3229 get_parameter_dek( para, pPASSPHRASE_DEK ),
3230 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3231 &pri_sk,
3232 timestamp,
3233 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3235 else
3237 /* Note, that depending on the backend, the card key generation
3238 may update TIMESTAMP. */
3239 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3240 &timestamp,
3241 get_parameter_u32 (para, pKEYEXPIRE), para);
3242 if (!rc)
3244 pri_sk = sec_root->next->pkt->pkt.secret_key;
3245 assert (pri_sk);
3249 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3251 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3252 if (!rc)
3253 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3256 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3258 write_uid (pub_root, s );
3259 write_uid (sec_root, s );
3261 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3262 get_parameter_uint (para, pKEYUSAGE), timestamp);
3265 /* Write the auth key to the card before the encryption key. This
3266 is a partial workaround for a PGP bug (as of this writing, all
3267 versions including 8.1), that causes it to try and encrypt to
3268 the most recent subkey regardless of whether that subkey is
3269 actually an encryption type. In this case, the auth key is an
3270 RSA key so it succeeds. */
3272 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3274 /* Note, that depending on the backend, the card key generation
3275 may update TIMESTAMP. */
3276 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3277 &timestamp,
3278 get_parameter_u32 (para, pKEYEXPIRE), para);
3280 if (!rc)
3281 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3282 PUBKEY_USAGE_AUTH, timestamp);
3283 if (!rc)
3284 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3285 PUBKEY_USAGE_AUTH, timestamp);
3288 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3290 if (!card)
3292 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
3293 get_parameter_uint( para, pSUBKEYLENGTH ),
3294 pub_root, sec_root,
3295 get_parameter_dek( para, pPASSPHRASE_DEK ),
3296 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3297 &sub_sk,
3298 timestamp,
3299 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3301 else
3303 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3305 /* A backup of the encryption key has been requested.
3306 Generate the key in software and import it then to
3307 the card. Write a backup file. */
3308 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3309 pub_root, sec_root,
3310 timestamp,
3311 get_parameter_u32 (para,
3312 pKEYEXPIRE),
3313 para, s);
3315 else
3317 /* Note, that depending on the backend, the card key
3318 generation may update TIMESTAMP. */
3319 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3320 NULL,
3321 &timestamp,
3322 get_parameter_u32 (para, pKEYEXPIRE), para);
3326 if( !rc )
3327 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3328 get_parameter_uint (para, pSUBKEYUSAGE),
3329 timestamp);
3330 if( !rc )
3331 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3332 get_parameter_uint (para, pSUBKEYUSAGE),
3333 timestamp);
3334 did_sub = 1;
3337 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3339 rc = write_keyblock( outctrl->pub.stream, pub_root );
3340 if (rc)
3341 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3342 if (!rc)
3344 rc = write_keyblock( outctrl->sec.stream, sec_root );
3345 if(rc)
3346 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3349 else if (!rc) /* Write to the standard keyrings. */
3351 KEYDB_HANDLE pub_hd = keydb_new (0);
3352 KEYDB_HANDLE sec_hd = keydb_new (1);
3354 rc = keydb_locate_writable (pub_hd, NULL);
3355 if (rc)
3356 log_error (_("no writable public keyring found: %s\n"),
3357 g10_errstr (rc));
3359 if (!rc)
3361 rc = keydb_locate_writable (sec_hd, NULL);
3362 if (rc)
3363 log_error (_("no writable secret keyring found: %s\n"),
3364 g10_errstr (rc));
3367 if (!rc && opt.verbose)
3369 log_info (_("writing public key to `%s'\n"),
3370 keydb_get_resource_name (pub_hd));
3371 if (card)
3372 log_info (_("writing secret key stub to `%s'\n"),
3373 keydb_get_resource_name (sec_hd));
3374 else
3375 log_info (_("writing secret key to `%s'\n"),
3376 keydb_get_resource_name (sec_hd));
3379 if (!rc)
3381 rc = keydb_insert_keyblock (pub_hd, pub_root);
3382 if (rc)
3383 log_error (_("error writing public keyring `%s': %s\n"),
3384 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3387 if (!rc)
3389 rc = keydb_insert_keyblock (sec_hd, sec_root);
3390 if (rc)
3391 log_error (_("error writing secret keyring `%s': %s\n"),
3392 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3395 keydb_release (pub_hd);
3396 keydb_release (sec_hd);
3398 if (!rc)
3400 int no_enc_rsa;
3401 PKT_public_key *pk;
3403 no_enc_rsa = (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
3404 && get_parameter_uint (para, pKEYUSAGE)
3405 && !((get_parameter_uint (para, pKEYUSAGE)
3406 & PUBKEY_USAGE_ENC)) );
3408 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3410 keyid_from_pk(pk,pk->main_keyid);
3411 register_trusted_keyid(pk->main_keyid);
3413 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3414 | TRUST_ULTIMATE ));
3416 if (!opt.batch)
3418 tty_printf (_("public and secret key created and signed.\n") );
3419 tty_printf ("\n");
3420 list_keyblock(pub_root,0,1,NULL);
3424 if (!opt.batch
3425 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
3426 || no_enc_rsa )
3427 && !get_parameter (para, pSUBKEYTYPE) )
3429 tty_printf(_("Note that this key cannot be used for "
3430 "encryption. You may want to use\n"
3431 "the command \"--edit-key\" to generate a "
3432 "subkey for this purpose.\n") );
3437 if (rc)
3439 if (opt.batch)
3440 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3441 else
3442 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3443 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3445 else
3447 PKT_public_key *pk = find_kbnode (pub_root,
3448 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3449 print_status_key_created (did_sub? 'B':'P', pk,
3450 get_parameter_value (para, pHANDLE));
3452 release_kbnode( pub_root );
3453 release_kbnode( sec_root );
3455 if (pri_sk && !card) /* The unprotected secret key unless we */
3456 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3457 if (sub_sk)
3458 free_secret_key(sub_sk);
3462 /* Add a new subkey to an existing key. Returns true if a new key has
3463 been generated and put into the keyblocks. */
3465 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3467 int okay=0, rc=0;
3468 KBNODE node;
3469 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3470 int algo;
3471 unsigned int use;
3472 u32 expire;
3473 unsigned nbits;
3474 char *passphrase = NULL;
3475 DEK *dek = NULL;
3476 STRING2KEY *s2k = NULL;
3477 u32 cur_time;
3478 int ask_pass = 0;
3479 int canceled;
3481 /* Break out the primary secret key. */
3482 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3483 if( !node )
3485 log_error ("Oops; secret key not found anymore!\n");
3486 goto leave;
3489 /* Make a copy of the sk to keep the protected one in the keyblock. */
3490 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3492 cur_time = make_timestamp();
3494 if (pri_sk->timestamp > cur_time)
3496 ulong d = pri_sk->timestamp - cur_time;
3497 log_info ( d==1 ? _("key has been created %lu second "
3498 "in future (time warp or clock problem)\n")
3499 : _("key has been created %lu seconds "
3500 "in future (time warp or clock problem)\n"), d );
3501 if (!opt.ignore_time_conflict)
3503 rc = G10ERR_TIME_CONFLICT;
3504 goto leave;
3508 if (pri_sk->version < 4)
3510 log_info (_("NOTE: creating subkeys for v3 keys "
3511 "is not OpenPGP compliant\n"));
3512 goto leave;
3515 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3517 tty_printf (_("Secret parts of primary key are not available.\n"));
3518 rc = G10ERR_NO_SECKEY;
3519 goto leave;
3523 /* Unprotect to get the passphrase. */
3524 switch (is_secret_key_protected (pri_sk) )
3526 case -1:
3527 rc = G10ERR_PUBKEY_ALGO;
3528 break;
3529 case 0:
3530 tty_printf (_("This key is not protected.\n"));
3531 break;
3532 case -2:
3533 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3534 ask_pass = 1;
3535 break;
3536 default:
3537 tty_printf (_("Key is protected.\n"));
3538 rc = check_secret_key ( pri_sk, 0 );
3539 if (!rc)
3540 passphrase = get_last_passphrase();
3541 break;
3543 if (rc)
3544 goto leave;
3546 algo = ask_algo (1, &use);
3547 assert (algo);
3548 nbits = ask_keysize (algo);
3549 expire = ask_expire_interval (0, NULL);
3550 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3551 _("Really create? (y/N) ")))
3552 goto leave;
3554 canceled = 0;
3555 if (ask_pass)
3556 dek = do_ask_passphrase (&s2k, &canceled);
3557 else if (passphrase)
3559 s2k = xmalloc_secure ( sizeof *s2k );
3560 s2k->mode = opt.s2k_mode;
3561 s2k->hash_algo = S2K_DIGEST_ALGO;
3562 set_next_passphrase ( passphrase );
3563 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3564 NULL, NULL );
3567 if (canceled)
3568 rc = GPG_ERR_CANCELED;
3570 if (!rc)
3571 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3572 dek, s2k, &sub_sk, cur_time, expire, 1 );
3573 if (!rc)
3574 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3575 use, cur_time);
3576 if (!rc)
3577 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3578 use, cur_time);
3579 if (!rc)
3581 okay = 1;
3582 write_status_text (STATUS_KEY_CREATED, "S");
3585 leave:
3586 if (rc)
3587 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3588 xfree (passphrase);
3589 xfree (dek);
3590 xfree (s2k);
3591 /* Release the copy of the (now unprotected) secret keys. */
3592 if (pri_sk)
3593 free_secret_key (pri_sk);
3594 if (sub_sk)
3595 free_secret_key (sub_sk);
3596 set_next_passphrase (NULL);
3597 return okay;
3601 #ifdef ENABLE_CARD_SUPPORT
3602 /* Generate a subkey on a card. */
3604 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3605 int keyno, const char *serialno)
3607 int okay=0, rc=0;
3608 KBNODE node;
3609 PKT_secret_key *pri_sk = NULL, *sub_sk;
3610 int algo;
3611 unsigned int use;
3612 u32 expire;
3613 char *passphrase = NULL;
3614 u32 cur_time;
3615 struct para_data_s *para = NULL;
3617 assert (keyno >= 1 && keyno <= 3);
3619 para = xcalloc (1, sizeof *para + strlen (serialno) );
3620 para->key = pSERIALNO;
3621 strcpy (para->u.value, serialno);
3623 /* Break out the primary secret key */
3624 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3625 if (!node)
3627 log_error("Oops; secret key not found anymore!\n");
3628 goto leave;
3631 /* Make a copy of the sk to keep the protected one in the keyblock */
3632 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3634 cur_time = make_timestamp();
3635 if (pri_sk->timestamp > cur_time)
3637 ulong d = pri_sk->timestamp - cur_time;
3638 log_info (d==1 ? _("key has been created %lu second "
3639 "in future (time warp or clock problem)\n")
3640 : _("key has been created %lu seconds "
3641 "in future (time warp or clock problem)\n"), d );
3642 if (!opt.ignore_time_conflict)
3644 rc = G10ERR_TIME_CONFLICT;
3645 goto leave;
3649 if (pri_sk->version < 4)
3651 log_info (_("NOTE: creating subkeys for v3 keys "
3652 "is not OpenPGP compliant\n"));
3653 goto leave;
3656 /* Unprotect to get the passphrase. */
3657 switch( is_secret_key_protected (pri_sk) )
3659 case -1:
3660 rc = G10ERR_PUBKEY_ALGO;
3661 break;
3662 case 0:
3663 tty_printf("This key is not protected.\n");
3664 break;
3665 default:
3666 tty_printf("Key is protected.\n");
3667 rc = check_secret_key( pri_sk, 0 );
3668 if (!rc)
3669 passphrase = get_last_passphrase();
3670 break;
3672 if (rc)
3673 goto leave;
3675 algo = PUBKEY_ALGO_RSA;
3676 expire = ask_expire_interval (0,NULL);
3677 if (keyno == 1)
3678 use = PUBKEY_USAGE_SIG;
3679 else if (keyno == 2)
3680 use = PUBKEY_USAGE_ENC;
3681 else
3682 use = PUBKEY_USAGE_AUTH;
3683 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3684 _("Really create? (y/N) ")))
3685 goto leave;
3687 if (passphrase)
3688 set_next_passphrase (passphrase);
3690 /* Note, that depending on the backend, the card key generation may
3691 update CUR_TIME. */
3692 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3693 &sub_sk, &cur_time, expire, para);
3694 if (!rc)
3695 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3696 use, cur_time);
3697 if (!rc)
3698 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3699 use, cur_time);
3700 if (!rc)
3702 okay = 1;
3703 write_status_text (STATUS_KEY_CREATED, "S");
3706 leave:
3707 if (rc)
3708 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3709 xfree (passphrase);
3710 /* Release the copy of the (now unprotected) secret keys. */
3711 if (pri_sk)
3712 free_secret_key (pri_sk);
3713 set_next_passphrase( NULL );
3714 release_parameter_list (para);
3715 return okay;
3717 #endif /* !ENABLE_CARD_SUPPORT */
3721 * Write a keyblock to an output stream
3723 static int
3724 write_keyblock( IOBUF out, KBNODE node )
3726 for( ; node ; node = node->next )
3728 if(!is_deleted_kbnode(node))
3730 int rc = build_packet( out, node->pkt );
3731 if( rc )
3733 log_error("build_packet(%d) failed: %s\n",
3734 node->pkt->pkttype, g10_errstr(rc) );
3735 return rc;
3740 return 0;
3744 /* Note that timestamp is an in/out arg. */
3745 static int
3746 gen_card_key (int algo, int keyno, int is_primary,
3747 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
3748 u32 *timestamp, u32 expireval, struct para_data_s *para)
3750 #ifdef ENABLE_CARD_SUPPORT
3751 int rc;
3752 const char *s;
3753 struct agent_card_genkey_s info;
3754 PACKET *pkt;
3755 PKT_secret_key *sk;
3756 PKT_public_key *pk;
3758 assert (algo == PUBKEY_ALGO_RSA);
3760 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3761 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
3762 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3763 /* { */
3764 /* tty_printf ("\n"); */
3765 /* log_error ("WARNING: key does already exists!\n"); */
3766 /* tty_printf ("\n"); */
3767 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3768 /* _("Replace existing key? "))) */
3769 /* rc = agent_scd_genkey (&info, keyno, 1); */
3770 /* } */
3772 if (rc)
3774 log_error ("key generation failed: %s\n", gpg_strerror (rc));
3775 return rc;
3777 if ( !info.n || !info.e )
3779 log_error ("communication error with SCD\n");
3780 gcry_mpi_release (info.n);
3781 gcry_mpi_release (info.e);
3782 return gpg_error (GPG_ERR_GENERAL);
3785 if (*timestamp != info.created_at)
3786 log_info ("Note that the key does not use the suggested creation date\n");
3787 *timestamp = info.created_at;
3789 pk = xcalloc (1, sizeof *pk );
3790 sk = xcalloc (1, sizeof *sk );
3791 sk->timestamp = pk->timestamp = info.created_at;
3792 sk->version = pk->version = 4;
3793 if (expireval)
3794 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
3795 sk->pubkey_algo = pk->pubkey_algo = algo;
3796 pk->pkey[0] = info.n;
3797 pk->pkey[1] = info.e;
3798 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
3799 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
3800 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3801 sk->is_protected = 1;
3802 sk->protect.s2k.mode = 1002;
3803 s = get_parameter_value (para, pSERIALNO);
3804 if (s)
3806 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3807 sk->protect.ivlen++, s += 2)
3808 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3811 if( ret_sk )
3812 *ret_sk = sk;
3814 pkt = xcalloc (1,sizeof *pkt);
3815 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
3816 pkt->pkt.public_key = pk;
3817 add_kbnode(pub_root, new_kbnode( pkt ));
3819 pkt = xcalloc (1,sizeof *pkt);
3820 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
3821 pkt->pkt.secret_key = sk;
3822 add_kbnode(sec_root, new_kbnode( pkt ));
3824 return 0;
3825 #else
3826 return -1;
3827 #endif /*!ENABLE_CARD_SUPPORT*/
3832 static int
3833 gen_card_key_with_backup (int algo, int keyno, int is_primary,
3834 KBNODE pub_root, KBNODE sec_root,
3835 u32 timestamp,
3836 u32 expireval, struct para_data_s *para,
3837 const char *backup_dir)
3839 #ifdef ENABLE_CARD_SUPPORT
3840 int rc;
3841 const char *s;
3842 PACKET *pkt;
3843 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
3844 PKT_public_key *pk;
3845 size_t n;
3846 int i;
3848 rc = generate_raw_key (algo, 1024, timestamp,
3849 &sk_unprotected, &sk_protected);
3850 if (rc)
3851 return rc;
3853 /* First, store the key to the card. */
3854 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
3855 if (rc)
3857 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
3858 free_secret_key (sk_unprotected);
3859 free_secret_key (sk_protected);
3860 return rc;
3863 /* Get rid of the secret key parameters and store the serial numer. */
3864 sk = sk_unprotected;
3865 n = pubkey_get_nskey (sk->pubkey_algo);
3866 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
3868 gcry_mpi_release (sk->skey[i]);
3869 sk->skey[i] = NULL;
3871 i = pubkey_get_npkey (sk->pubkey_algo);
3872 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3873 sk->is_protected = 1;
3874 sk->protect.s2k.mode = 1002;
3875 s = get_parameter_value (para, pSERIALNO);
3876 assert (s);
3877 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3878 sk->protect.ivlen++, s += 2)
3879 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3881 /* Now write the *protected* secret key to the file. */
3883 char name_buffer[50];
3884 char *fname;
3885 IOBUF fp;
3886 mode_t oldmask;
3888 keyid_from_sk (sk, NULL);
3889 sprintf (name_buffer,"sk_%08lX%08lX.gpg",
3890 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
3892 fname = make_filename (backup_dir, name_buffer, NULL);
3893 oldmask = umask (077);
3894 if (is_secured_filename (fname))
3896 fp = NULL;
3897 errno = EPERM;
3899 else
3900 fp = iobuf_create (fname);
3901 umask (oldmask);
3902 if (!fp)
3904 rc = gpg_error_from_syserror ();
3905 log_error (_("can't create backup file `%s': %s\n"),
3906 fname, strerror(errno) );
3907 xfree (fname);
3908 free_secret_key (sk_unprotected);
3909 free_secret_key (sk_protected);
3910 return rc;
3913 pkt = xcalloc (1, sizeof *pkt);
3914 pkt->pkttype = PKT_SECRET_KEY;
3915 pkt->pkt.secret_key = sk_protected;
3916 sk_protected = NULL;
3918 rc = build_packet (fp, pkt);
3919 if (rc)
3921 log_error("build packet failed: %s\n", g10_errstr(rc) );
3922 iobuf_cancel (fp);
3924 else
3926 unsigned char array[MAX_FINGERPRINT_LEN];
3927 char *fprbuf, *p;
3929 iobuf_close (fp);
3930 iobuf_ioctl (NULL, 2, 0, (char*)fname);
3931 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
3933 fingerprint_from_sk (sk, array, &n);
3934 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
3935 for (i=0; i < n ; i++, p += 2)
3936 sprintf (p, "%02X", array[i]);
3937 *p++ = ' ';
3938 *p = 0;
3940 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
3941 fprbuf,
3942 fname, strlen (fname),
3944 xfree (fprbuf);
3946 free_packet (pkt);
3947 xfree (pkt);
3948 xfree (fname);
3949 if (rc)
3951 free_secret_key (sk_unprotected);
3952 return rc;
3956 /* Create the public key from the secret key. */
3957 pk = xcalloc (1, sizeof *pk );
3958 pk->timestamp = sk->timestamp;
3959 pk->version = sk->version;
3960 if (expireval)
3961 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
3962 pk->pubkey_algo = sk->pubkey_algo;
3963 n = pubkey_get_npkey (sk->pubkey_algo);
3964 for (i=0; i < n; i++)
3965 pk->pkey[i] = mpi_copy (sk->skey[i]);
3967 /* Build packets and add them to the node lists. */
3968 pkt = xcalloc (1,sizeof *pkt);
3969 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
3970 pkt->pkt.public_key = pk;
3971 add_kbnode(pub_root, new_kbnode( pkt ));
3973 pkt = xcalloc (1,sizeof *pkt);
3974 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
3975 pkt->pkt.secret_key = sk;
3976 add_kbnode(sec_root, new_kbnode( pkt ));
3978 return 0;
3979 #else
3980 return -1;
3981 #endif /*!ENABLE_CARD_SUPPORT*/
3985 #ifdef ENABLE_CARD_SUPPORT
3987 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
3989 int rc;
3990 unsigned char *rsa_n = NULL;
3991 unsigned char *rsa_e = NULL;
3992 unsigned char *rsa_p = NULL;
3993 unsigned char *rsa_q = NULL;
3994 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
3995 unsigned char *sexp = NULL;
3996 unsigned char *p;
3997 char numbuf[55], numbuf2[50];
3999 assert (is_RSA (sk->pubkey_algo));
4000 assert (!sk->is_protected);
4002 /* Copy the parameters into straight buffers. */
4003 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4004 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4005 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4006 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4007 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4009 rc = G10ERR_INV_ARG;
4010 goto leave;
4013 /* Put the key into an S-expression. */
4014 sexp = p = xmalloc_secure (30
4015 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4016 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4018 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4019 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4020 p = stpcpy (p, numbuf);
4021 memcpy (p, rsa_n, rsa_n_len);
4022 p += rsa_n_len;
4024 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4025 p = stpcpy (p, numbuf);
4026 memcpy (p, rsa_e, rsa_e_len);
4027 p += rsa_e_len;
4029 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4030 p = stpcpy (p, numbuf);
4031 memcpy (p, rsa_p, rsa_p_len);
4032 p += rsa_p_len;
4034 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4035 p = stpcpy (p, numbuf);
4036 memcpy (p, rsa_q, rsa_q_len);
4037 p += rsa_q_len;
4039 p = stpcpy (p,"))(10:created-at");
4040 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4041 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4042 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4044 /* Fixme: Unfortunately we don't have the serialnumber available -
4045 thus we can't pass it down to the agent. */
4046 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4048 leave:
4049 xfree (sexp);
4050 xfree (rsa_n);
4051 xfree (rsa_e);
4052 xfree (rsa_p);
4053 xfree (rsa_q);
4054 return rc;
4056 #endif /*ENABLE_CARD_SUPPORT*/