Fix bug#1122.
[gnupg.git] / g10 / keygen.c
blob3abc19bd056588478e199922d6800b3c734913ef
1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
32 #include "gpg.h"
33 #include "util.h"
34 #include "main.h"
35 #include "packet.h"
36 #include "cipher.h"
37 #include "ttyio.h"
38 #include "options.h"
39 #include "keydb.h"
40 #include "trustdb.h"
41 #include "status.h"
42 #include "i18n.h"
43 #include "keyserver-internal.h"
44 #include "call-agent.h"
47 #define MAX_PREFS 30
49 enum para_name {
50 pKEYTYPE,
51 pKEYLENGTH,
52 pKEYUSAGE,
53 pSUBKEYTYPE,
54 pSUBKEYLENGTH,
55 pSUBKEYUSAGE,
56 pAUTHKEYTYPE,
57 pNAMEREAL,
58 pNAMEEMAIL,
59 pNAMECOMMENT,
60 pPREFERENCES,
61 pREVOKER,
62 pUSERID,
63 pCREATIONDATE,
64 pKEYCREATIONDATE, /* Same in seconds since epoch. */
65 pEXPIREDATE,
66 pKEYEXPIRE, /* in n seconds */
67 pSUBKEYEXPIRE, /* in n seconds */
68 pPASSPHRASE,
69 pPASSPHRASE_DEK,
70 pPASSPHRASE_S2K,
71 pSERIALNO,
72 pBACKUPENCDIR,
73 pHANDLE,
74 pKEYSERVER
77 struct para_data_s {
78 struct para_data_s *next;
79 int lnr;
80 enum para_name key;
81 union {
82 DEK *dek;
83 STRING2KEY *s2k;
84 u32 expire;
85 u32 creation;
86 unsigned int usage;
87 struct revocation_key revkey;
88 char value[1];
89 } u;
92 struct output_control_s {
93 int lnr;
94 int dryrun;
95 int ask_passphrase;
96 int use_files;
97 struct {
98 char *fname;
99 char *newfname;
100 IOBUF stream;
101 armor_filter_context_t *afx;
102 } pub;
103 struct {
104 char *fname;
105 char *newfname;
106 IOBUF stream;
107 armor_filter_context_t *afx;
108 } sec;
112 struct opaque_data_usage_and_pk {
113 unsigned int usage;
114 PKT_public_key *pk;
118 static int prefs_initialized = 0;
119 static byte sym_prefs[MAX_PREFS];
120 static int nsym_prefs;
121 static byte hash_prefs[MAX_PREFS];
122 static int nhash_prefs;
123 static byte zip_prefs[MAX_PREFS];
124 static int nzip_prefs;
125 static int mdc_available,ks_modify;
127 static void do_generate_keypair( struct para_data_s *para,
128 struct output_control_s *outctrl, int card );
129 static int write_keyblock( IOBUF out, KBNODE node );
130 static int gen_card_key (int algo, int keyno, int is_primary,
131 KBNODE pub_root, KBNODE sec_root,
132 PKT_secret_key **ret_sk,
133 u32 *timestamp,
134 u32 expireval, struct para_data_s *para);
135 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
136 KBNODE pub_root, KBNODE sec_root,
137 u32 timestamp,
138 u32 expireval, struct para_data_s *para,
139 const char *backup_dir);
142 static void
143 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
145 byte array[MAX_FINGERPRINT_LEN], *s;
146 char *buf, *p;
147 size_t i, n;
149 if (!handle)
150 handle = "";
152 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
154 p = buf;
155 if (letter || pk)
157 *p++ = letter;
158 *p++ = ' ';
159 fingerprint_from_pk (pk, array, &n);
160 s = array;
161 for (i=0; i < n ; i++, s++, p += 2)
162 sprintf (p, "%02X", *s);
164 if (*handle)
166 *p++ = ' ';
167 for (i=0; handle[i] && i < 100; i++)
168 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
170 *p = 0;
171 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
172 buf);
173 xfree (buf);
176 static void
177 print_status_key_not_created (const char *handle)
179 print_status_key_created (0, NULL, handle);
184 static void
185 write_uid( KBNODE root, const char *s )
187 PACKET *pkt = xmalloc_clear(sizeof *pkt );
188 size_t n = strlen(s);
190 pkt->pkttype = PKT_USER_ID;
191 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
192 pkt->pkt.user_id->len = n;
193 pkt->pkt.user_id->ref = 1;
194 strcpy(pkt->pkt.user_id->name, s);
195 add_kbnode( root, new_kbnode( pkt ) );
198 static void
199 do_add_key_flags (PKT_signature *sig, unsigned int use)
201 byte buf[1];
203 buf[0] = 0;
205 /* The spec says that all primary keys MUST be able to certify. */
206 if(sig->sig_class!=0x18)
207 buf[0] |= 0x01;
209 if (use & PUBKEY_USAGE_SIG)
210 buf[0] |= 0x02;
211 if (use & PUBKEY_USAGE_ENC)
212 buf[0] |= 0x04 | 0x08;
213 if (use & PUBKEY_USAGE_AUTH)
214 buf[0] |= 0x20;
216 if (!buf[0])
217 return;
219 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
224 keygen_add_key_expire( PKT_signature *sig, void *opaque )
226 PKT_public_key *pk = opaque;
227 byte buf[8];
228 u32 u;
230 if( pk->expiredate ) {
231 if(pk->expiredate > pk->timestamp)
232 u= pk->expiredate - pk->timestamp;
233 else
234 u= 1;
236 buf[0] = (u >> 24) & 0xff;
237 buf[1] = (u >> 16) & 0xff;
238 buf[2] = (u >> 8) & 0xff;
239 buf[3] = u & 0xff;
240 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
242 else
244 /* Make sure we don't leave a key expiration subpacket lying
245 around */
246 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
249 return 0;
252 static int
253 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
255 struct opaque_data_usage_and_pk *oduap = opaque;
257 do_add_key_flags (sig, oduap->usage);
258 return keygen_add_key_expire (sig, oduap->pk);
261 static int
262 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
264 int i;
266 for (i=0; i < *nbuf; i++ )
267 if (buf[i] == val)
269 log_info (_("preference `%s' duplicated\n"), item);
270 return -1;
273 if (*nbuf >= MAX_PREFS)
275 if(type==1)
276 log_info(_("too many cipher preferences\n"));
277 else if(type==2)
278 log_info(_("too many digest preferences\n"));
279 else if(type==3)
280 log_info(_("too many compression preferences\n"));
281 else
282 BUG();
284 return -1;
287 buf[(*nbuf)++] = val;
288 return 0;
292 * Parse the supplied string and use it to set the standard
293 * preferences. The string may be in a form like the one printed by
294 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
295 * cipher/hash/compress names. Use NULL to set the default
296 * preferences. Returns: 0 = okay
299 keygen_set_std_prefs (const char *string,int personal)
301 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
302 int nsym=0, nhash=0, nzip=0, val, rc=0;
303 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
304 char dummy_string[20*4+1]; /* Enough for 20 items. */
306 if (!string || !ascii_strcasecmp (string, "default"))
308 if (opt.def_preference_list)
309 string=opt.def_preference_list;
310 else
312 dummy_string[0]='\0';
314 /* The rationale why we use the order AES256,192,128 is
315 for compatibility reasons with PGP. If gpg would
316 define AES128 first, we would get the somewhat
317 confusing situation:
319 gpg -r pgpkey -r gpgkey ---gives--> AES256
320 gpg -r gpgkey -r pgpkey ---gives--> AES
322 Note that by using --personal-cipher-preferences it is
323 possible to prefer AES128.
326 /* Make sure we do not add more than 15 items here, as we
327 could overflow the size of dummy_string. We currently
328 have at most 12. */
329 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
330 strcat(dummy_string,"S9 ");
331 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
332 strcat(dummy_string,"S8 ");
333 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
334 strcat(dummy_string,"S7 ");
335 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
336 strcat(dummy_string,"S3 ");
337 strcat(dummy_string,"S2 "); /* 3DES */
338 /* If we have it, IDEA goes *after* 3DES so it won't be
339 used unless we're encrypting along with a V3 key.
340 Ideally, we would only put the S1 preference in if the
341 key was RSA and <=2048 bits, as that is what won't
342 break PGP2, but that is difficult with the current
343 code, and not really worth checking as a non-RSA <=2048
344 bit key wouldn't be usable by PGP2 anyway. -dms */
345 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
346 strcat(dummy_string,"S1 ");
349 /* The default hash algo order is:
350 SHA-256, SHA-1, SHA-384, SHA-512, SHA-224.
351 Ordering SHA-1 before SHA-384 might be viewed as a bit
352 strange; it is done because we expect that soon enough
353 SHA-3 will be available and at that point there should
354 be no more need for SHA-384 etc. Anyway this order is
355 just a default and can easily be changed by a config
356 option. */
357 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
358 strcat (dummy_string, "H8 ");
360 strcat (dummy_string, "H2 "); /* SHA-1 */
362 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
363 strcat (dummy_string, "H9 ");
365 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
366 strcat (dummy_string, "H10 ");
368 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
369 strcat (dummy_string, "H11 ");
372 /* ZLIB */
373 strcat(dummy_string,"Z2 ");
375 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
376 strcat(dummy_string,"Z3 ");
378 /* ZIP */
379 strcat(dummy_string,"Z1");
381 string=dummy_string;
384 else if (!ascii_strcasecmp (string, "none"))
385 string = "";
387 if(strlen(string))
389 char *tok,*prefstring;
391 prefstring=xstrdup(string); /* need a writable string! */
393 while((tok=strsep(&prefstring," ,")))
395 if((val=string_to_cipher_algo (tok)))
397 if(set_one_pref(val,1,tok,sym,&nsym))
398 rc=-1;
400 else if((val=string_to_digest_algo (tok)))
402 if(set_one_pref(val,2,tok,hash,&nhash))
403 rc=-1;
405 else if((val=string_to_compress_algo(tok))>-1)
407 if(set_one_pref(val,3,tok,zip,&nzip))
408 rc=-1;
410 else if (ascii_strcasecmp(tok,"mdc")==0)
411 mdc=1;
412 else if (ascii_strcasecmp(tok,"no-mdc")==0)
413 mdc=0;
414 else if (ascii_strcasecmp(tok,"ks-modify")==0)
415 modify=1;
416 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
417 modify=0;
418 else
420 log_info (_("invalid item `%s' in preference string\n"),tok);
422 /* Complain if IDEA is not available. */
423 if(ascii_strcasecmp(tok,"s1")==0
424 || ascii_strcasecmp(tok,"idea")==0)
425 idea_cipher_warn(1);
427 rc=-1;
431 xfree(prefstring);
434 if(!rc)
436 if(personal)
438 if(personal==PREFTYPE_SYM)
440 xfree(opt.personal_cipher_prefs);
442 if(nsym==0)
443 opt.personal_cipher_prefs=NULL;
444 else
446 int i;
448 opt.personal_cipher_prefs=
449 xmalloc(sizeof(prefitem_t *)*(nsym+1));
451 for (i=0; i<nsym; i++)
453 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
454 opt.personal_cipher_prefs[i].value = sym[i];
457 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
458 opt.personal_cipher_prefs[i].value = 0;
461 else if(personal==PREFTYPE_HASH)
463 xfree(opt.personal_digest_prefs);
465 if(nhash==0)
466 opt.personal_digest_prefs=NULL;
467 else
469 int i;
471 opt.personal_digest_prefs=
472 xmalloc(sizeof(prefitem_t *)*(nhash+1));
474 for (i=0; i<nhash; i++)
476 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
477 opt.personal_digest_prefs[i].value = hash[i];
480 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
481 opt.personal_digest_prefs[i].value = 0;
484 else if(personal==PREFTYPE_ZIP)
486 xfree(opt.personal_compress_prefs);
488 if(nzip==0)
489 opt.personal_compress_prefs=NULL;
490 else
492 int i;
494 opt.personal_compress_prefs=
495 xmalloc(sizeof(prefitem_t *)*(nzip+1));
497 for (i=0; i<nzip; i++)
499 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
500 opt.personal_compress_prefs[i].value = zip[i];
503 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
504 opt.personal_compress_prefs[i].value = 0;
508 else
510 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
511 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
512 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
513 mdc_available = mdc;
514 ks_modify = modify;
515 prefs_initialized = 1;
519 return rc;
522 /* Return a fake user ID containing the preferences. Caller must
523 free. */
524 PKT_user_id *
525 keygen_get_std_prefs(void)
527 int i,j=0;
528 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
530 if(!prefs_initialized)
531 keygen_set_std_prefs(NULL,0);
533 uid->ref=1;
535 uid->prefs=xmalloc((sizeof(prefitem_t *)*
536 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
538 for(i=0;i<nsym_prefs;i++,j++)
540 uid->prefs[j].type=PREFTYPE_SYM;
541 uid->prefs[j].value=sym_prefs[i];
544 for(i=0;i<nhash_prefs;i++,j++)
546 uid->prefs[j].type=PREFTYPE_HASH;
547 uid->prefs[j].value=hash_prefs[i];
550 for(i=0;i<nzip_prefs;i++,j++)
552 uid->prefs[j].type=PREFTYPE_ZIP;
553 uid->prefs[j].value=zip_prefs[i];
556 uid->prefs[j].type=PREFTYPE_NONE;
557 uid->prefs[j].value=0;
559 uid->flags.mdc=mdc_available;
560 uid->flags.ks_modify=ks_modify;
562 return uid;
565 static void
566 add_feature_mdc (PKT_signature *sig,int enabled)
568 const byte *s;
569 size_t n;
570 int i;
571 char *buf;
573 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
574 /* Already set or cleared */
575 if (s && n &&
576 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
577 return;
579 if (!s || !n) { /* create a new one */
580 n = 1;
581 buf = xmalloc_clear (n);
583 else {
584 buf = xmalloc (n);
585 memcpy (buf, s, n);
588 if(enabled)
589 buf[0] |= 0x01; /* MDC feature */
590 else
591 buf[0] &= ~0x01;
593 /* Are there any bits set? */
594 for(i=0;i<n;i++)
595 if(buf[i]!=0)
596 break;
598 if(i==n)
599 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
600 else
601 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
603 xfree (buf);
606 static void
607 add_keyserver_modify (PKT_signature *sig,int enabled)
609 const byte *s;
610 size_t n;
611 int i;
612 char *buf;
614 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
615 enabled=!enabled;
617 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
618 /* Already set or cleared */
619 if (s && n &&
620 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
621 return;
623 if (!s || !n) { /* create a new one */
624 n = 1;
625 buf = xmalloc_clear (n);
627 else {
628 buf = xmalloc (n);
629 memcpy (buf, s, n);
632 if(enabled)
633 buf[0] |= 0x80; /* no-modify flag */
634 else
635 buf[0] &= ~0x80;
637 /* Are there any bits set? */
638 for(i=0;i<n;i++)
639 if(buf[i]!=0)
640 break;
642 if(i==n)
643 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
644 else
645 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
647 xfree (buf);
652 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
654 (void)opaque;
656 if (!prefs_initialized)
657 keygen_set_std_prefs (NULL, 0);
659 if (nsym_prefs)
660 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
661 else
663 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
664 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
667 if (nhash_prefs)
668 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
669 else
671 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
672 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
675 if (nzip_prefs)
676 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
677 else
679 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
680 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
683 /* Make sure that the MDC feature flag is set if needed. */
684 add_feature_mdc (sig,mdc_available);
685 add_keyserver_modify (sig,ks_modify);
686 keygen_add_keyserver_url(sig,NULL);
688 return 0;
692 /****************
693 * Add preference to the self signature packet.
694 * This is only called for packets with version > 3.
698 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
700 PKT_public_key *pk = opaque;
702 do_add_key_flags (sig, pk->pubkey_usage);
703 keygen_add_key_expire( sig, opaque );
704 keygen_upd_std_prefs (sig, opaque);
705 keygen_add_keyserver_url(sig,NULL);
707 return 0;
711 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
713 const char *url=opaque;
715 if(!url)
716 url=opt.def_keyserver_url;
718 if(url)
719 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
720 else
721 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
723 return 0;
727 keygen_add_notations(PKT_signature *sig,void *opaque)
729 struct notation *notation;
731 /* We always start clean */
732 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
733 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
734 sig->flags.notation=0;
736 for(notation=opaque;notation;notation=notation->next)
737 if(!notation->flags.ignore)
739 unsigned char *buf;
740 unsigned int n1,n2;
742 n1=strlen(notation->name);
743 if(notation->altvalue)
744 n2=strlen(notation->altvalue);
745 else if(notation->bdat)
746 n2=notation->blen;
747 else
748 n2=strlen(notation->value);
750 buf = xmalloc( 8 + n1 + n2 );
752 /* human readable or not */
753 buf[0] = notation->bdat?0:0x80;
754 buf[1] = buf[2] = buf[3] = 0;
755 buf[4] = n1 >> 8;
756 buf[5] = n1;
757 buf[6] = n2 >> 8;
758 buf[7] = n2;
759 memcpy(buf+8, notation->name, n1 );
760 if(notation->altvalue)
761 memcpy(buf+8+n1, notation->altvalue, n2 );
762 else if(notation->bdat)
763 memcpy(buf+8+n1, notation->bdat, n2 );
764 else
765 memcpy(buf+8+n1, notation->value, n2 );
766 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
767 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
768 buf, 8+n1+n2 );
769 xfree(buf);
772 return 0;
776 keygen_add_revkey(PKT_signature *sig, void *opaque)
778 struct revocation_key *revkey=opaque;
779 byte buf[2+MAX_FINGERPRINT_LEN];
781 buf[0]=revkey->class;
782 buf[1]=revkey->algid;
783 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
785 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
787 /* All sigs with revocation keys set are nonrevocable */
788 sig->flags.revocable=0;
789 buf[0] = 0;
790 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
792 parse_revkeys(sig);
794 return 0;
799 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
800 signature creation time. */
802 make_backsig (PKT_signature *sig,PKT_public_key *pk,
803 PKT_public_key *sub_pk,PKT_secret_key *sub_sk,
804 u32 timestamp)
806 PKT_signature *backsig;
807 int rc;
809 cache_public_key(sub_pk);
811 rc = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_sk, 0x19,
812 0, 0, timestamp, 0, NULL, NULL);
813 if(rc)
814 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
815 else
817 /* Get it into a binary packed form. */
818 IOBUF backsig_out=iobuf_temp();
819 PACKET backsig_pkt;
821 init_packet(&backsig_pkt);
822 backsig_pkt.pkttype=PKT_SIGNATURE;
823 backsig_pkt.pkt.signature=backsig;
824 rc=build_packet(backsig_out,&backsig_pkt);
825 free_packet(&backsig_pkt);
826 if(rc)
827 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
828 else
830 size_t pktlen=0;
831 byte *buf=iobuf_get_temp_buffer(backsig_out);
833 /* Remove the packet header */
834 if(buf[0]&0x40)
836 if(buf[1]<192)
838 pktlen=buf[1];
839 buf+=2;
841 else if(buf[1]<224)
843 pktlen=(buf[1]-192)*256;
844 pktlen+=buf[2]+192;
845 buf+=3;
847 else if(buf[1]==255)
849 pktlen =buf[2] << 24;
850 pktlen|=buf[3] << 16;
851 pktlen|=buf[4] << 8;
852 pktlen|=buf[5];
853 buf+=6;
855 else
856 BUG();
858 else
860 int mark=1;
862 switch(buf[0]&3)
864 case 3:
865 BUG();
866 break;
868 case 2:
869 pktlen =buf[mark++] << 24;
870 pktlen|=buf[mark++] << 16;
872 case 1:
873 pktlen|=buf[mark++] << 8;
875 case 0:
876 pktlen|=buf[mark++];
879 buf+=mark;
882 /* Now make the binary blob into a subpacket. */
883 build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
885 iobuf_close(backsig_out);
889 return rc;
893 static int
894 write_direct_sig (KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
895 struct revocation_key *revkey, u32 timestamp)
897 PACKET *pkt;
898 PKT_signature *sig;
899 int rc=0;
900 KBNODE node;
901 PKT_public_key *pk;
903 if( opt.verbose )
904 log_info(_("writing direct signature\n"));
906 /* Get the pk packet from the pub_tree. */
907 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
908 if( !node )
909 BUG();
910 pk = node->pkt->pkt.public_key;
912 /* We have to cache the key, so that the verification of the
913 signature creation is able to retrieve the public key. */
914 cache_public_key (pk);
916 /* Make the signature. */
917 rc = make_keysig_packet (&sig,pk,NULL,NULL,sk,0x1F,
918 0, 0, timestamp, 0,
919 keygen_add_revkey, revkey);
920 if( rc )
922 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
923 return rc;
926 pkt = xmalloc_clear( sizeof *pkt );
927 pkt->pkttype = PKT_SIGNATURE;
928 pkt->pkt.signature = sig;
929 add_kbnode( root, new_kbnode( pkt ) );
930 return rc;
934 static int
935 write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
936 unsigned int use, u32 timestamp )
938 PACKET *pkt;
939 PKT_signature *sig;
940 PKT_user_id *uid;
941 int rc=0;
942 KBNODE node;
943 PKT_public_key *pk;
945 if( opt.verbose )
946 log_info(_("writing self signature\n"));
948 /* Get the uid packet from the list. */
949 node = find_kbnode( pub_root, PKT_USER_ID );
950 if( !node )
951 BUG(); /* No user id packet in tree. */
952 uid = node->pkt->pkt.user_id;
954 /* Get the pk packet from the pub_tree. */
955 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
956 if( !node )
957 BUG();
958 pk = node->pkt->pkt.public_key;
959 pk->pubkey_usage = use;
961 /* We have to cache the key, so that the verification of the
962 signature creation is able to retrieve the public key. */
963 cache_public_key (pk);
965 /* Make the signature. */
966 rc = make_keysig_packet (&sig, pk, uid, NULL, sk, 0x13,
967 0, 0, timestamp, 0,
968 keygen_add_std_prefs, pk);
969 if( rc )
971 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
972 return rc;
975 pkt = xmalloc_clear( sizeof *pkt );
976 pkt->pkttype = PKT_SIGNATURE;
977 pkt->pkt.signature = sig;
978 add_kbnode( sec_root, new_kbnode( pkt ) );
980 pkt = xmalloc_clear( sizeof *pkt );
981 pkt->pkttype = PKT_SIGNATURE;
982 pkt->pkt.signature = copy_signature(NULL,sig);
983 add_kbnode( pub_root, new_kbnode( pkt ) );
984 return rc;
988 /* Write the key binding signature. If TIMESTAMP is not NULL use the
989 signature creation times. */
990 static int
991 write_keybinding (KBNODE root, KBNODE pub_root,
992 PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
993 unsigned int use, u32 timestamp)
995 PACKET *pkt;
996 PKT_signature *sig;
997 int rc=0;
998 KBNODE node;
999 PKT_public_key *pri_pk, *sub_pk;
1000 struct opaque_data_usage_and_pk oduap;
1002 if ( opt.verbose )
1003 log_info(_("writing key binding signature\n"));
1005 /* Get the pk packet from the pub_tree. */
1006 node = find_kbnode ( pub_root, PKT_PUBLIC_KEY );
1007 if ( !node )
1008 BUG();
1009 pri_pk = node->pkt->pkt.public_key;
1011 /* We have to cache the key, so that the verification of the
1012 * signature creation is able to retrieve the public key. */
1013 cache_public_key (pri_pk);
1015 /* Find the last subkey. */
1016 sub_pk = NULL;
1017 for (node=pub_root; node; node = node->next )
1019 if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
1020 sub_pk = node->pkt->pkt.public_key;
1022 if (!sub_pk)
1023 BUG();
1025 /* Make the signature. */
1026 oduap.usage = use;
1027 oduap.pk = sub_pk;
1028 rc = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18,
1029 0, 0, timestamp, 0,
1030 keygen_add_key_flags_and_expire, &oduap );
1031 if (rc)
1033 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc) );
1034 return rc;
1037 /* Make a backsig. */
1038 if (use&PUBKEY_USAGE_SIG)
1040 rc = make_backsig (sig, pri_pk, sub_pk, sub_sk, timestamp);
1041 if (rc)
1042 return rc;
1045 pkt = xmalloc_clear ( sizeof *pkt );
1046 pkt->pkttype = PKT_SIGNATURE;
1047 pkt->pkt.signature = sig;
1048 add_kbnode (root, new_kbnode (pkt) );
1049 return rc;
1054 static int
1055 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1056 const char *topname, const char *elems)
1058 gcry_sexp_t list, l2;
1059 const char *s;
1060 int i, idx;
1061 int rc = 0;
1063 list = gcry_sexp_find_token (sexp, topname, 0);
1064 if (!list)
1065 return gpg_error (GPG_ERR_INV_OBJ);
1066 l2 = gcry_sexp_cadr (list);
1067 gcry_sexp_release (list);
1068 list = l2;
1069 if (!list)
1070 return gpg_error (GPG_ERR_NO_OBJ);
1072 for (idx=0,s=elems; *s; s++, idx++)
1074 l2 = gcry_sexp_find_token (list, s, 1);
1075 if (!l2)
1077 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1078 goto leave;
1080 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1081 gcry_sexp_release (l2);
1082 if (!array[idx])
1084 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1085 goto leave;
1088 gcry_sexp_release (list);
1090 leave:
1091 if (rc)
1093 for (i=0; i<idx; i++)
1095 xfree (array[i]);
1096 array[i] = NULL;
1098 gcry_sexp_release (list);
1100 return rc;
1104 static int
1105 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
1107 int rc = 0;
1109 if (dek)
1111 sk->protect.algo = dek->algo;
1112 sk->protect.s2k = *s2k;
1113 rc = protect_secret_key (sk, dek);
1114 if (rc)
1115 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
1118 return rc;
1121 static void
1122 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
1124 (void)misc_key_info;
1125 (void)sec_root;
1126 #if 0 /* Not used anymore */
1127 size_t n;
1128 char *buf;
1130 if (misc_key_info)
1132 /* DSA: don't know whether it makes sense to have the factors, so for now
1133 we store them in the secret keyring (but they are not secret)
1134 p = 2 * q * f1 * f2 * ... * fn
1135 We store only f1 to f_n-1; fn can be calculated because p and q
1136 are known. */
1137 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
1138 buf = xmalloc (n+4);
1139 strcpy (buf, "#::");
1140 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
1141 if (n)
1143 n += 3;
1144 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
1146 xfree (buf);
1147 gcry_sexp_release (misc_key_info);
1149 #endif
1153 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1154 time to be put into the key structure. */
1155 static int
1156 gen_elg (int algo, unsigned int nbits,
1157 KBNODE pub_root, KBNODE sec_root, DEK *dek,
1158 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1159 u32 timestamp, u32 expireval, int is_subkey)
1161 int rc;
1162 PACKET *pkt;
1163 PKT_secret_key *sk;
1164 PKT_public_key *pk;
1165 gcry_sexp_t s_parms, s_key;
1166 gcry_sexp_t misc_key_info;
1168 assert( is_ELGAMAL(algo) );
1170 if (nbits < 512)
1172 nbits = 1024;
1173 log_info (_("keysize invalid; using %u bits\n"), nbits );
1176 if ((nbits % 32))
1178 nbits = ((nbits + 31) / 32) * 32;
1179 log_info (_("keysize rounded up to %u bits\n"), nbits );
1183 rc = gcry_sexp_build ( &s_parms, NULL,
1184 "(genkey(%s(nbits %d)))",
1185 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1186 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1187 (int)nbits);
1188 if (rc)
1189 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1191 rc = gcry_pk_genkey (&s_key, s_parms);
1192 gcry_sexp_release (s_parms);
1193 if (rc)
1195 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1196 return rc;
1199 sk = xmalloc_clear( sizeof *sk );
1200 pk = xmalloc_clear( sizeof *pk );
1201 sk->timestamp = pk->timestamp = timestamp;
1202 sk->version = pk->version = 4;
1203 if (expireval)
1205 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1207 sk->pubkey_algo = pk->pubkey_algo = algo;
1209 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
1210 if (rc)
1212 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1213 gcry_sexp_release (s_key);
1214 free_secret_key (sk);
1215 free_public_key (pk);
1216 return rc;
1218 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
1219 if (rc)
1221 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1222 gcry_sexp_release (s_key);
1223 free_secret_key (sk);
1224 free_public_key (pk);
1225 return rc;
1227 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1228 gcry_sexp_release (s_key);
1230 sk->is_protected = 0;
1231 sk->protect.algo = 0;
1233 sk->csum = checksum_mpi (sk->skey[3]);
1234 if (ret_sk) /* Return an unprotected version of the sk. */
1235 *ret_sk = copy_secret_key ( NULL, sk );
1237 rc = genhelp_protect (dek, s2k, sk);
1238 if (rc)
1240 free_public_key (pk);
1241 free_secret_key (sk);
1242 gcry_sexp_release (misc_key_info);
1243 return rc;
1246 pkt = xmalloc_clear (sizeof *pkt);
1247 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1248 pkt->pkt.public_key = pk;
1249 add_kbnode (pub_root, new_kbnode( pkt ));
1251 /* Don't know whether it makes sense to have access to the factors,
1252 so for now we store them in the secret keyring (but they are not
1253 secret). */
1254 pkt = xmalloc_clear (sizeof *pkt);
1255 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1256 pkt->pkt.secret_key = sk;
1257 add_kbnode (sec_root, new_kbnode( pkt ));
1259 genhelp_factors (misc_key_info, sec_root);
1261 return 0;
1265 /****************
1266 * Generate a DSA key
1268 static int
1269 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1270 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1271 u32 timestamp, u32 expireval, int is_subkey)
1273 int rc;
1274 PACKET *pkt;
1275 PKT_secret_key *sk;
1276 PKT_public_key *pk;
1277 gcry_sexp_t s_parms, s_key;
1278 gcry_sexp_t misc_key_info;
1279 unsigned int qbits;
1281 if ( nbits < 512)
1283 nbits = 1024;
1284 log_info(_("keysize invalid; using %u bits\n"), nbits );
1286 else if ( nbits > 3072 )
1288 nbits = 3072;
1289 log_info(_("keysize invalid; using %u bits\n"), nbits );
1292 if( (nbits % 64) )
1294 nbits = ((nbits + 63) / 64) * 64;
1295 log_info(_("keysize rounded up to %u bits\n"), nbits );
1298 /* To comply with FIPS rules we round up to the next value unless in
1299 expert mode. */
1300 if (!opt.expert && nbits > 1024 && (nbits % 1024))
1302 nbits = ((nbits + 1023) / 1024) * 1024;
1303 log_info(_("keysize rounded up to %u bits\n"), nbits );
1307 Figure out a q size based on the key size. FIPS 180-3 says:
1309 L = 1024, N = 160
1310 L = 2048, N = 224
1311 L = 2048, N = 256
1312 L = 3072, N = 256
1314 2048/256 is an odd pair since there is also a 2048/224 and
1315 3072/256. Matching sizes is not a very exact science.
1317 We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1318 but less than 2048, and 160 for 1024 (DSA1).
1321 if (nbits > 2047)
1322 qbits = 256;
1323 else if ( nbits > 1024)
1324 qbits = 224;
1325 else
1326 qbits = 160;
1328 if (qbits != 160 )
1329 log_info (_("WARNING: some OpenPGP programs can't"
1330 " handle a DSA key with this digest size\n"));
1332 rc = gcry_sexp_build (&s_parms, NULL,
1333 "(genkey(dsa(nbits %d)(qbits %d)))",
1334 (int)nbits, (int)qbits);
1335 if (rc)
1336 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1338 rc = gcry_pk_genkey (&s_key, s_parms);
1339 gcry_sexp_release (s_parms);
1340 if (rc)
1342 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1343 return rc;
1346 sk = xmalloc_clear( sizeof *sk );
1347 pk = xmalloc_clear( sizeof *pk );
1348 sk->timestamp = pk->timestamp = timestamp;
1349 sk->version = pk->version = 4;
1350 if (expireval)
1351 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1352 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1354 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1355 if (rc)
1357 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1358 gcry_sexp_release (s_key);
1359 free_public_key(pk);
1360 free_secret_key(sk);
1361 return rc;
1363 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1364 if (rc)
1366 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1367 gcry_sexp_release (s_key);
1368 free_public_key(pk);
1369 free_secret_key(sk);
1370 return rc;
1372 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1373 gcry_sexp_release (s_key);
1375 sk->is_protected = 0;
1376 sk->protect.algo = 0;
1378 sk->csum = checksum_mpi ( sk->skey[4] );
1379 if( ret_sk ) /* return an unprotected version of the sk */
1380 *ret_sk = copy_secret_key( NULL, sk );
1382 rc = genhelp_protect (dek, s2k, sk);
1383 if (rc)
1385 free_public_key (pk);
1386 free_secret_key (sk);
1387 gcry_sexp_release (misc_key_info);
1388 return rc;
1391 pkt = xmalloc_clear(sizeof *pkt);
1392 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1393 pkt->pkt.public_key = pk;
1394 add_kbnode(pub_root, new_kbnode( pkt ));
1396 /* Don't know whether it makes sense to have the factors, so for now
1397 * we store them in the secret keyring (but they are not secret)
1398 * p = 2 * q * f1 * f2 * ... * fn
1399 * We store only f1 to f_n-1; fn can be calculated because p and q
1400 * are known.
1402 pkt = xmalloc_clear(sizeof *pkt);
1403 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1404 pkt->pkt.secret_key = sk;
1405 add_kbnode(sec_root, new_kbnode( pkt ));
1407 genhelp_factors (misc_key_info, sec_root);
1409 return 0;
1414 * Generate an RSA key.
1416 static int
1417 gen_rsa (int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1418 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1419 u32 timestamp, u32 expireval, int is_subkey)
1421 int rc;
1422 PACKET *pkt;
1423 PKT_secret_key *sk;
1424 PKT_public_key *pk;
1425 gcry_sexp_t s_parms, s_key;
1427 assert (is_RSA(algo));
1429 if (nbits < 1024)
1431 nbits = 1024;
1432 log_info (_("keysize invalid; using %u bits\n"), nbits );
1435 if ((nbits % 32))
1437 nbits = ((nbits + 31) / 32) * 32;
1438 log_info (_("keysize rounded up to %u bits\n"), nbits );
1441 rc = gcry_sexp_build (&s_parms, NULL,
1442 "(genkey(rsa(nbits %d)))",
1443 (int)nbits);
1444 if (rc)
1445 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1447 rc = gcry_pk_genkey (&s_key, s_parms);
1448 gcry_sexp_release (s_parms);
1449 if (rc)
1451 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1452 return rc;
1455 sk = xmalloc_clear( sizeof *sk );
1456 pk = xmalloc_clear( sizeof *pk );
1457 sk->timestamp = pk->timestamp = timestamp;
1458 sk->version = pk->version = 4;
1459 if (expireval)
1461 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1463 sk->pubkey_algo = pk->pubkey_algo = algo;
1465 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1466 if (rc)
1468 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1469 gcry_sexp_release (s_key);
1470 free_public_key(pk);
1471 free_secret_key(sk);
1472 return rc;
1474 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1475 if (rc)
1477 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1478 gcry_sexp_release (s_key);
1479 free_public_key(pk);
1480 free_secret_key(sk);
1481 return rc;
1483 gcry_sexp_release (s_key);
1485 sk->is_protected = 0;
1486 sk->protect.algo = 0;
1488 sk->csum = checksum_mpi (sk->skey[2] );
1489 sk->csum += checksum_mpi (sk->skey[3] );
1490 sk->csum += checksum_mpi (sk->skey[4] );
1491 sk->csum += checksum_mpi (sk->skey[5] );
1492 if( ret_sk ) /* return an unprotected version of the sk */
1493 *ret_sk = copy_secret_key( NULL, sk );
1495 rc = genhelp_protect (dek, s2k, sk);
1496 if (rc)
1498 free_public_key (pk);
1499 free_secret_key (sk);
1500 return rc;
1503 pkt = xmalloc_clear(sizeof *pkt);
1504 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1505 pkt->pkt.public_key = pk;
1506 add_kbnode(pub_root, new_kbnode( pkt ));
1508 pkt = xmalloc_clear(sizeof *pkt);
1509 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1510 pkt->pkt.secret_key = sk;
1511 add_kbnode(sec_root, new_kbnode( pkt ));
1513 return 0;
1517 /****************
1518 * check valid days:
1519 * return 0 on error or the multiplier
1521 static int
1522 check_valid_days( const char *s )
1524 if( !digitp(s) )
1525 return 0;
1526 for( s++; *s; s++)
1527 if( !digitp(s) )
1528 break;
1529 if( !*s )
1530 return 1;
1531 if( s[1] )
1532 return 0; /* e.g. "2323wc" */
1533 if( *s == 'd' || *s == 'D' )
1534 return 1;
1535 if( *s == 'w' || *s == 'W' )
1536 return 7;
1537 if( *s == 'm' || *s == 'M' )
1538 return 30;
1539 if( *s == 'y' || *s == 'Y' )
1540 return 365;
1541 return 0;
1545 static void
1546 print_key_flags(int flags)
1548 if(flags&PUBKEY_USAGE_SIG)
1549 tty_printf("%s ",_("Sign"));
1551 if(flags&PUBKEY_USAGE_CERT)
1552 tty_printf("%s ",_("Certify"));
1554 if(flags&PUBKEY_USAGE_ENC)
1555 tty_printf("%s ",_("Encrypt"));
1557 if(flags&PUBKEY_USAGE_AUTH)
1558 tty_printf("%s ",_("Authenticate"));
1562 /* Returns the key flags */
1563 static unsigned int
1564 ask_key_flags(int algo,int subkey)
1566 /* TRANSLATORS: Please use only plain ASCII characters for the
1567 translation. If this is not possible use single digits. The
1568 string needs to 8 bytes long. Here is a description of the
1569 functions:
1571 s = Toggle signing capability
1572 e = Toggle encryption capability
1573 a = Toggle authentication capability
1574 q = Finish
1576 const char *togglers=_("SsEeAaQq");
1577 char *answer=NULL;
1578 unsigned int current=0;
1579 unsigned int possible=openpgp_pk_algo_usage(algo);
1581 if ( strlen(togglers) != 8 )
1583 tty_printf ("NOTE: Bad translation at %s:%d. "
1584 "Please report.\n", __FILE__, __LINE__);
1585 togglers = "11223300";
1588 /* Only primary keys may certify. */
1589 if(subkey)
1590 possible&=~PUBKEY_USAGE_CERT;
1592 /* Preload the current set with the possible set, minus
1593 authentication, since nobody really uses auth yet. */
1594 current=possible&~PUBKEY_USAGE_AUTH;
1596 for(;;)
1598 tty_printf("\n");
1599 tty_printf(_("Possible actions for a %s key: "),
1600 gcry_pk_algo_name (algo));
1601 print_key_flags(possible);
1602 tty_printf("\n");
1603 tty_printf(_("Current allowed actions: "));
1604 print_key_flags(current);
1605 tty_printf("\n\n");
1607 if(possible&PUBKEY_USAGE_SIG)
1608 tty_printf(_(" (%c) Toggle the sign capability\n"),
1609 togglers[0]);
1610 if(possible&PUBKEY_USAGE_ENC)
1611 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1612 togglers[2]);
1613 if(possible&PUBKEY_USAGE_AUTH)
1614 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1615 togglers[4]);
1617 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1618 tty_printf("\n");
1620 xfree(answer);
1621 answer = cpr_get("keygen.flags",_("Your selection? "));
1622 cpr_kill_prompt();
1624 if(strlen(answer)>1)
1625 tty_printf(_("Invalid selection.\n"));
1626 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1627 break;
1628 else if((*answer==togglers[0] || *answer==togglers[1])
1629 && possible&PUBKEY_USAGE_SIG)
1631 if(current&PUBKEY_USAGE_SIG)
1632 current&=~PUBKEY_USAGE_SIG;
1633 else
1634 current|=PUBKEY_USAGE_SIG;
1636 else if((*answer==togglers[2] || *answer==togglers[3])
1637 && possible&PUBKEY_USAGE_ENC)
1639 if(current&PUBKEY_USAGE_ENC)
1640 current&=~PUBKEY_USAGE_ENC;
1641 else
1642 current|=PUBKEY_USAGE_ENC;
1644 else if((*answer==togglers[4] || *answer==togglers[5])
1645 && possible&PUBKEY_USAGE_AUTH)
1647 if(current&PUBKEY_USAGE_AUTH)
1648 current&=~PUBKEY_USAGE_AUTH;
1649 else
1650 current|=PUBKEY_USAGE_AUTH;
1652 else
1653 tty_printf(_("Invalid selection.\n"));
1656 xfree(answer);
1658 return current;
1662 /* Ask for an algorithm. The function returns the algorithm id to
1663 * create. If ADDMODE is false the function won't show an option to
1664 * create the primary and subkey combined and won't set R_USAGE
1665 * either. If a combined algorithm has been selected, the subkey
1666 * algorithm is stored at R_SUBKEY_ALGO. */
1667 static int
1668 ask_algo (int addmode, int *r_subkey_algo, unsigned int *r_usage)
1670 char *answer;
1671 int algo;
1672 int dummy_algo;
1674 if (!r_subkey_algo)
1675 r_subkey_algo = &dummy_algo;
1677 tty_printf (_("Please select what kind of key you want:\n"));
1679 if (!addmode)
1680 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1681 if (!addmode)
1682 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1684 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1685 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1687 if (addmode)
1689 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1690 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1692 if (opt.expert)
1694 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1695 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1698 for(;;)
1700 *r_usage = 0;
1701 *r_subkey_algo = 0;
1702 answer = cpr_get ("keygen.algo", _("Your selection? "));
1703 cpr_kill_prompt ();
1704 algo = *answer? atoi (answer) : 1;
1705 xfree(answer);
1706 if (algo == 1 && !addmode)
1708 algo = PUBKEY_ALGO_RSA;
1709 *r_subkey_algo = PUBKEY_ALGO_RSA;
1710 break;
1712 else if (algo == 2 && !addmode)
1714 algo = PUBKEY_ALGO_DSA;
1715 *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1716 break;
1718 else if (algo == 3)
1720 algo = PUBKEY_ALGO_DSA;
1721 *r_usage = PUBKEY_USAGE_SIG;
1722 break;
1724 else if (algo == 4)
1726 algo = PUBKEY_ALGO_RSA;
1727 *r_usage = PUBKEY_USAGE_SIG;
1728 break;
1730 else if (algo == 5 && addmode)
1732 algo = PUBKEY_ALGO_ELGAMAL_E;
1733 *r_usage = PUBKEY_USAGE_ENC;
1734 break;
1736 else if (algo == 6 && addmode)
1738 algo = PUBKEY_ALGO_RSA;
1739 *r_usage = PUBKEY_USAGE_ENC;
1740 break;
1742 else if (algo == 7 && opt.expert)
1744 algo = PUBKEY_ALGO_DSA;
1745 *r_usage = ask_key_flags (algo, addmode);
1746 break;
1748 else if (algo == 8 && opt.expert)
1750 algo = PUBKEY_ALGO_RSA;
1751 *r_usage = ask_key_flags (algo, addmode);
1752 break;
1754 else
1755 tty_printf (_("Invalid selection.\n"));
1758 return algo;
1762 /* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
1763 is not 0, the function asks for the size of the encryption
1764 subkey. */
1765 static unsigned
1766 ask_keysize (int algo, unsigned int primary_keysize)
1768 unsigned int nbits, min, def=2048, max=4096;
1769 int for_subkey = !!primary_keysize;
1770 int autocomp = 0;
1772 if(opt.expert)
1773 min=512;
1774 else
1775 min=1024;
1777 if (primary_keysize && !opt.expert)
1779 /* Deduce the subkey size from the primary key size. */
1780 if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
1781 nbits = 3072; /* For performance reasons we don't support more
1782 than 3072 bit DSA. However we won't see this
1783 case anyway because DSA can't be used as an
1784 encryption subkey ;-). */
1785 else
1786 nbits = primary_keysize;
1787 autocomp = 1;
1788 goto leave;
1791 switch(algo)
1793 case PUBKEY_ALGO_DSA:
1794 def=2048;
1795 max=3072;
1796 break;
1798 case PUBKEY_ALGO_RSA:
1799 min=1024;
1800 break;
1803 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1804 gcry_pk_algo_name (algo), min, max);
1806 for(;;)
1808 char *prompt, *answer;
1810 if (for_subkey)
1811 prompt = xasprintf (_("What keysize do you want "
1812 "for the subkey? (%u) "), def);
1813 else
1814 prompt = xasprintf (_("What keysize do you want? (%u) "), def);
1815 answer = cpr_get ("keygen.size", prompt);
1816 cpr_kill_prompt ();
1817 nbits = *answer? atoi (answer): def;
1818 xfree(prompt);
1819 xfree(answer);
1821 if(nbits<min || nbits>max)
1822 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1823 gcry_pk_algo_name (algo), min, max);
1824 else
1825 break;
1828 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1830 leave:
1831 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
1833 nbits = ((nbits + 63) / 64) * 64;
1834 if (!autocomp)
1835 tty_printf(_("rounded up to %u bits\n"), nbits );
1837 else if( (nbits % 32) )
1839 nbits = ((nbits + 31) / 32) * 32;
1840 if (!autocomp)
1841 tty_printf(_("rounded up to %u bits\n"), nbits );
1844 return nbits;
1848 /****************
1849 * Parse an expire string and return its value in seconds.
1850 * Returns (u32)-1 on error.
1851 * This isn't perfect since scan_isodatestr returns unix time, and
1852 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1853 * Because of this, we only permit setting expirations up to 2106, but
1854 * OpenPGP could theoretically allow up to 2242. I think we'll all
1855 * just cope for the next few years until we get a 64-bit time_t or
1856 * similar.
1859 parse_expire_string( const char *string )
1861 int mult;
1862 u32 seconds;
1863 u32 abs_date = 0;
1864 u32 curtime = make_timestamp ();
1865 time_t tt;
1867 if (!*string)
1868 seconds = 0;
1869 else if (!strncmp (string, "seconds=", 8))
1870 seconds = atoi (string+8);
1871 else if ((abs_date = scan_isodatestr(string))
1872 && (abs_date+86400/2) > curtime)
1873 seconds = (abs_date+86400/2) - curtime;
1874 else if ((tt = isotime2epoch (string)) != (time_t)(-1))
1875 seconds = (u32)tt - curtime;
1876 else if ((mult = check_valid_days (string)))
1877 seconds = atoi (string) * 86400L * mult;
1878 else
1879 seconds = (u32)(-1);
1881 return seconds;
1884 /* Parsean Creation-Date string which is either "1986-04-26" or
1885 "19860426T042640". Returns 0 on error. */
1886 static u32
1887 parse_creation_string (const char *string)
1889 u32 seconds;
1891 if (!*string)
1892 seconds = 0;
1893 else if ( !strncmp (string, "seconds=", 8) )
1894 seconds = atoi (string+8);
1895 else if ( !(seconds = scan_isodatestr (string)))
1897 time_t tmp = isotime2epoch (string);
1898 seconds = (tmp == (time_t)(-1))? 0 : tmp;
1900 return seconds;
1904 /* object == 0 for a key, and 1 for a sig */
1906 ask_expire_interval(int object,const char *def_expire)
1908 u32 interval;
1909 char *answer;
1911 switch(object)
1913 case 0:
1914 if(def_expire)
1915 BUG();
1916 tty_printf(_("Please specify how long the key should be valid.\n"
1917 " 0 = key does not expire\n"
1918 " <n> = key expires in n days\n"
1919 " <n>w = key expires in n weeks\n"
1920 " <n>m = key expires in n months\n"
1921 " <n>y = key expires in n years\n"));
1922 break;
1924 case 1:
1925 if(!def_expire)
1926 BUG();
1927 tty_printf(_("Please specify how long the signature should be valid.\n"
1928 " 0 = signature does not expire\n"
1929 " <n> = signature expires in n days\n"
1930 " <n>w = signature expires in n weeks\n"
1931 " <n>m = signature expires in n months\n"
1932 " <n>y = signature expires in n years\n"));
1933 break;
1935 default:
1936 BUG();
1939 /* Note: The elgamal subkey for DSA has no expiration date because
1940 * it must be signed with the DSA key and this one has the expiration
1941 * date */
1943 answer = NULL;
1944 for(;;)
1946 u32 curtime=make_timestamp();
1948 xfree(answer);
1949 if(object==0)
1950 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1951 else
1953 char *prompt;
1955 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1956 /* This will actually end up larger than necessary because
1957 of the 2 bytes for '%s' */
1958 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
1959 sprintf(prompt,PROMPTSTRING,def_expire);
1960 #undef PROMPTSTRING
1962 answer = cpr_get("siggen.valid",prompt);
1963 xfree(prompt);
1965 if(*answer=='\0')
1966 answer=xstrdup(def_expire);
1968 cpr_kill_prompt();
1969 trim_spaces(answer);
1970 interval = parse_expire_string( answer );
1971 if( interval == (u32)-1 )
1973 tty_printf(_("invalid value\n"));
1974 continue;
1977 if( !interval )
1979 tty_printf((object==0)
1980 ? _("Key does not expire at all\n")
1981 : _("Signature does not expire at all\n"));
1983 else
1985 tty_printf(object==0
1986 ? _("Key expires at %s\n")
1987 : _("Signature expires at %s\n"),
1988 asctimestamp((ulong)(curtime + interval) ) );
1989 #if SIZEOF_TIME_T <= 4
1990 if ( (time_t)((ulong)(curtime+interval)) < 0 )
1991 tty_printf (_("Your system can't display dates beyond 2038.\n"
1992 "However, it will be correctly handled up to"
1993 " 2106.\n"));
1994 else
1995 #endif /*SIZEOF_TIME_T*/
1996 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
1998 tty_printf (_("invalid value\n"));
1999 continue;
2003 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2004 _("Is this correct? (y/N) ")) )
2005 break;
2008 xfree(answer);
2009 return interval;
2013 ask_expiredate()
2015 u32 x = ask_expire_interval(0,NULL);
2016 return x? make_timestamp() + x : 0;
2021 static PKT_user_id *
2022 uid_from_string (const char *string)
2024 size_t n;
2025 PKT_user_id *uid;
2027 n = strlen (string);
2028 uid = xmalloc_clear (sizeof *uid + n);
2029 uid->len = n;
2030 strcpy (uid->name, string);
2031 uid->ref = 1;
2032 return uid;
2036 /* Ask for a user ID. With a MODE of 1 an extra help prompt is
2037 printed for use during a new key creation. If KEYBLOCK is not NULL
2038 the function prevents the creation of an already existing user
2039 ID. */
2040 static char *
2041 ask_user_id (int mode, KBNODE keyblock)
2043 char *answer;
2044 char *aname, *acomment, *amail, *uid;
2046 if ( !mode )
2048 /* TRANSLATORS: This is the new string telling the user what
2049 gpg is now going to do (i.e. ask for the parts of the user
2050 ID). Note that if you do not tyranslated this string, a
2051 different string will be used used, which might still have
2052 a correct transaltion. */
2053 const char *s1 =
2054 N_("\n"
2055 "GnuPG needs to construct a user ID to identify your key.\n"
2056 "\n");
2057 const char *s2 = _(s1);
2059 if (!strcmp (s1, s2))
2061 /* There is no translation for the string thus we to use
2062 the old info text. gettext has no way to tell whether
2063 a translation is actually available, thus we need to
2064 to compare again. */
2065 /* TRANSLATORS: This string is in general not anymore used
2066 but you should keep your existing translation. In case
2067 the new string is not translated this old string will
2068 be used. */
2069 const char *s3 = N_("\n"
2070 "You need a user ID to identify your key; "
2071 "the software constructs the user ID\n"
2072 "from the Real Name, Comment and Email Address in this form:\n"
2073 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2074 const char *s4 = _(s3);
2075 if (strcmp (s3, s4))
2076 s2 = s3; /* A translation exists - use it. */
2078 tty_printf ("%s", s2) ;
2080 uid = aname = acomment = amail = NULL;
2081 for(;;) {
2082 char *p;
2083 int fail=0;
2085 if( !aname ) {
2086 for(;;) {
2087 xfree(aname);
2088 aname = cpr_get("keygen.name",_("Real name: "));
2089 trim_spaces(aname);
2090 cpr_kill_prompt();
2092 if( opt.allow_freeform_uid )
2093 break;
2095 if( strpbrk( aname, "<>" ) )
2096 tty_printf(_("Invalid character in name\n"));
2097 else if( digitp(aname) )
2098 tty_printf(_("Name may not start with a digit\n"));
2099 else if( strlen(aname) < 5 )
2100 tty_printf(_("Name must be at least 5 characters long\n"));
2101 else
2102 break;
2105 if( !amail ) {
2106 for(;;) {
2107 xfree(amail);
2108 amail = cpr_get("keygen.email",_("Email address: "));
2109 trim_spaces(amail);
2110 cpr_kill_prompt();
2111 if( !*amail || opt.allow_freeform_uid )
2112 break; /* no email address is okay */
2113 else if ( !is_valid_mailbox (amail) )
2114 tty_printf(_("Not a valid email address\n"));
2115 else
2116 break;
2119 if( !acomment ) {
2120 for(;;) {
2121 xfree(acomment);
2122 acomment = cpr_get("keygen.comment",_("Comment: "));
2123 trim_spaces(acomment);
2124 cpr_kill_prompt();
2125 if( !*acomment )
2126 break; /* no comment is okay */
2127 else if( strpbrk( acomment, "()" ) )
2128 tty_printf(_("Invalid character in comment\n"));
2129 else
2130 break;
2135 xfree(uid);
2136 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2137 p = stpcpy(p, aname );
2138 if( *acomment )
2139 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2140 if( *amail )
2141 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2143 /* Append a warning if the RNG is switched into fake mode. */
2144 if ( random_is_faked () )
2145 strcpy(p, " (insecure!)" );
2147 /* print a note in case that UTF8 mapping has to be done */
2148 for(p=uid; *p; p++ ) {
2149 if( *p & 0x80 ) {
2150 tty_printf(_("You are using the `%s' character set.\n"),
2151 get_native_charset() );
2152 break;
2156 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2158 if( !*amail && !opt.allow_freeform_uid
2159 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2160 fail = 1;
2161 tty_printf(_("Please don't put the email address "
2162 "into the real name or the comment\n") );
2165 if (!fail && keyblock)
2167 PKT_user_id *uidpkt = uid_from_string (uid);
2168 KBNODE node;
2170 for (node=keyblock; node && !fail; node=node->next)
2171 if (!is_deleted_kbnode (node)
2172 && node->pkt->pkttype == PKT_USER_ID
2173 && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
2174 fail = 1;
2175 if (fail)
2176 tty_printf (_("Such a user ID already exists on this key!\n"));
2177 free_user_id (uidpkt);
2180 for(;;) {
2181 /* TRANSLATORS: These are the allowed answers in
2182 lower and uppercase. Below you will find the matching
2183 string which should be translated accordingly and the
2184 letter changed to match the one in the answer string.
2186 n = Change name
2187 c = Change comment
2188 e = Change email
2189 o = Okay (ready, continue)
2190 q = Quit
2192 const char *ansstr = _("NnCcEeOoQq");
2194 if( strlen(ansstr) != 10 )
2195 BUG();
2196 if( cpr_enabled() ) {
2197 answer = xstrdup(ansstr+6);
2198 answer[1] = 0;
2200 else {
2201 answer = cpr_get("keygen.userid.cmd", fail?
2202 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2203 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2204 cpr_kill_prompt();
2206 if( strlen(answer) > 1 )
2208 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2209 xfree(aname); aname = NULL;
2210 break;
2212 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2213 xfree(acomment); acomment = NULL;
2214 break;
2216 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2217 xfree(amail); amail = NULL;
2218 break;
2220 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2221 if( fail ) {
2222 tty_printf(_("Please correct the error first\n"));
2224 else {
2225 xfree(aname); aname = NULL;
2226 xfree(acomment); acomment = NULL;
2227 xfree(amail); amail = NULL;
2228 break;
2231 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2232 xfree(aname); aname = NULL;
2233 xfree(acomment); acomment = NULL;
2234 xfree(amail); amail = NULL;
2235 xfree(uid); uid = NULL;
2236 break;
2238 xfree(answer);
2240 xfree(answer);
2241 if( !amail && !acomment && !amail )
2242 break;
2243 xfree(uid); uid = NULL;
2245 if( uid ) {
2246 char *p = native_to_utf8( uid );
2247 xfree( uid );
2248 uid = p;
2250 return uid;
2254 /* MODE 0 - standard
2255 1 - Ask for passphrase of the card backup key. */
2256 static DEK *
2257 do_ask_passphrase (STRING2KEY **ret_s2k, int mode, int *r_canceled)
2259 DEK *dek = NULL;
2260 STRING2KEY *s2k;
2261 const char *errtext = NULL;
2262 const char *custdesc = NULL;
2264 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2266 if (mode == 1)
2267 custdesc = _("Please enter a passphrase to protect the off-card "
2268 "backup of the new encryption key.");
2270 s2k = xmalloc_secure( sizeof *s2k );
2271 for(;;) {
2272 s2k->mode = opt.s2k_mode;
2273 s2k->hash_algo = S2K_DIGEST_ALGO;
2274 dek = passphrase_to_dek_ext (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2275 errtext, custdesc, NULL, r_canceled);
2276 if (!dek && *r_canceled) {
2277 xfree(dek); dek = NULL;
2278 xfree(s2k); s2k = NULL;
2279 break;
2281 else if( !dek ) {
2282 errtext = N_("passphrase not correctly repeated; try again");
2283 tty_printf(_("%s.\n"), _(errtext));
2285 else if( !dek->keylen ) {
2286 xfree(dek); dek = NULL;
2287 xfree(s2k); s2k = NULL;
2288 tty_printf(_(
2289 "You don't want a passphrase - this is probably a *bad* idea!\n"
2290 "I will do it anyway. You can change your passphrase at any time,\n"
2291 "using this program with the option \"--edit-key\".\n\n"));
2292 break;
2294 else
2295 break; /* okay */
2297 *ret_s2k = s2k;
2298 return dek;
2302 /* Basic key generation. Here we divert to the actual generation
2303 routines based on the requested algorithm. */
2304 static int
2305 do_create (int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
2306 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk,
2307 u32 timestamp, u32 expiredate, int is_subkey )
2309 int rc=0;
2311 if( !opt.batch )
2312 tty_printf(_(
2313 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2314 "some other action (type on the keyboard, move the mouse, utilize the\n"
2315 "disks) during the prime generation; this gives the random number\n"
2316 "generator a better chance to gain enough entropy.\n") );
2318 if( algo == PUBKEY_ALGO_ELGAMAL_E )
2319 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2320 timestamp, expiredate, is_subkey);
2321 else if( algo == PUBKEY_ALGO_DSA )
2322 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk,
2323 timestamp, expiredate, is_subkey);
2324 else if( algo == PUBKEY_ALGO_RSA )
2325 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2326 timestamp, expiredate, is_subkey);
2327 else
2328 BUG();
2330 return rc;
2334 /* Generate a new user id packet or return NULL if canceled. If
2335 KEYBLOCK is not NULL the function prevents the creation of an
2336 already existing user ID. */
2337 PKT_user_id *
2338 generate_user_id (KBNODE keyblock)
2340 char *p;
2342 p = ask_user_id (1, keyblock);
2343 if (!p)
2344 return NULL; /* Canceled. */
2345 return uid_from_string (p);
2349 static void
2350 release_parameter_list( struct para_data_s *r )
2352 struct para_data_s *r2;
2354 for( ; r ; r = r2 ) {
2355 r2 = r->next;
2356 if( r->key == pPASSPHRASE_DEK )
2357 xfree( r->u.dek );
2358 else if( r->key == pPASSPHRASE_S2K )
2359 xfree( r->u.s2k );
2361 xfree(r);
2365 static struct para_data_s *
2366 get_parameter( struct para_data_s *para, enum para_name key )
2368 struct para_data_s *r;
2370 for( r = para; r && r->key != key; r = r->next )
2372 return r;
2375 static const char *
2376 get_parameter_value( struct para_data_s *para, enum para_name key )
2378 struct para_data_s *r = get_parameter( para, key );
2379 return (r && *r->u.value)? r->u.value : NULL;
2382 static int
2383 get_parameter_algo( struct para_data_s *para, enum para_name key )
2385 int i;
2386 struct para_data_s *r = get_parameter( para, key );
2387 if( !r )
2388 return -1;
2389 if( digitp( r->u.value ) )
2390 i = atoi( r->u.value );
2391 else if ( !strcmp ( r->u.value, "ELG-E")
2392 || !strcmp ( r->u.value, "ELG") )
2393 i = GCRY_PK_ELG_E;
2394 else
2395 i = gcry_pk_map_name (r->u.value);
2396 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2397 i = 0; /* we don't want to allow generation of these algorithms */
2398 return i;
2402 * Parse the usage parameter and set the keyflags. Returns -1 on
2403 * error, 0 for no usage given or 1 for usage available.
2405 static int
2406 parse_parameter_usage (const char *fname,
2407 struct para_data_s *para, enum para_name key)
2409 struct para_data_s *r = get_parameter( para, key );
2410 char *p, *pn;
2411 unsigned int use;
2413 if( !r )
2414 return 0; /* none (this is an optional parameter)*/
2416 use = 0;
2417 pn = r->u.value;
2418 while ( (p = strsep (&pn, " \t,")) ) {
2419 if ( !*p)
2421 else if ( !ascii_strcasecmp (p, "sign") )
2422 use |= PUBKEY_USAGE_SIG;
2423 else if ( !ascii_strcasecmp (p, "encrypt") )
2424 use |= PUBKEY_USAGE_ENC;
2425 else if ( !ascii_strcasecmp (p, "auth") )
2426 use |= PUBKEY_USAGE_AUTH;
2427 else {
2428 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2429 return -1; /* error */
2432 r->u.usage = use;
2433 return 1;
2436 static int
2437 parse_revocation_key (const char *fname,
2438 struct para_data_s *para, enum para_name key)
2440 struct para_data_s *r = get_parameter( para, key );
2441 struct revocation_key revkey;
2442 char *pn;
2443 int i;
2445 if( !r )
2446 return 0; /* none (this is an optional parameter) */
2448 pn = r->u.value;
2450 revkey.class=0x80;
2451 revkey.algid=atoi(pn);
2452 if(!revkey.algid)
2453 goto fail;
2455 /* Skip to the fpr */
2456 while(*pn && *pn!=':')
2457 pn++;
2459 if(*pn!=':')
2460 goto fail;
2462 pn++;
2464 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2466 int c=hextobyte(pn);
2467 if(c==-1)
2468 goto fail;
2470 revkey.fpr[i]=c;
2473 /* skip to the tag */
2474 while(*pn && *pn!='s' && *pn!='S')
2475 pn++;
2477 if(ascii_strcasecmp(pn,"sensitive")==0)
2478 revkey.class|=0x40;
2480 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2482 return 0;
2484 fail:
2485 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2486 return -1; /* error */
2490 static u32
2491 get_parameter_u32( struct para_data_s *para, enum para_name key )
2493 struct para_data_s *r = get_parameter( para, key );
2495 if( !r )
2496 return 0;
2497 if( r->key == pKEYCREATIONDATE )
2498 return r->u.creation;
2499 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2500 return r->u.expire;
2501 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2502 return r->u.usage;
2504 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2507 static unsigned int
2508 get_parameter_uint( struct para_data_s *para, enum para_name key )
2510 return get_parameter_u32( para, key );
2513 static DEK *
2514 get_parameter_dek( struct para_data_s *para, enum para_name key )
2516 struct para_data_s *r = get_parameter( para, key );
2517 return r? r->u.dek : NULL;
2520 static STRING2KEY *
2521 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2523 struct para_data_s *r = get_parameter( para, key );
2524 return r? r->u.s2k : NULL;
2527 static struct revocation_key *
2528 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2530 struct para_data_s *r = get_parameter( para, key );
2531 return r? &r->u.revkey : NULL;
2534 static int
2535 proc_parameter_file( struct para_data_s *para, const char *fname,
2536 struct output_control_s *outctrl, int card )
2538 struct para_data_s *r;
2539 const char *s1, *s2, *s3;
2540 size_t n;
2541 char *p;
2542 int have_user_id=0,err,algo;
2544 /* Check that we have all required parameters. */
2545 r = get_parameter( para, pKEYTYPE );
2546 if(r)
2548 algo=get_parameter_algo(para,pKEYTYPE);
2549 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2551 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2552 return -1;
2555 else
2557 log_error ("%s: no Key-Type specified\n",fname);
2558 return -1;
2561 err = parse_parameter_usage (fname, para, pKEYUSAGE);
2562 if (!err)
2564 /* Default to algo capabilities if key-usage is not provided */
2565 r = xmalloc_clear(sizeof(*r));
2566 r->key = pKEYUSAGE;
2567 r->u.usage = openpgp_pk_algo_usage(algo);
2568 r->next = para;
2569 para = r;
2571 else if (err == -1)
2572 return -1;
2573 else
2575 r = get_parameter (para, pKEYUSAGE);
2576 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2578 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2579 fname, r->lnr, algo);
2580 return -1;
2584 r = get_parameter( para, pSUBKEYTYPE );
2585 if(r)
2587 algo = get_parameter_algo (para, pSUBKEYTYPE);
2588 if (openpgp_pk_test_algo (algo))
2590 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2591 return -1;
2594 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2595 if (!err)
2597 /* Default to algo capabilities if subkey-usage is not
2598 provided */
2599 r = xmalloc_clear (sizeof(*r));
2600 r->key = pSUBKEYUSAGE;
2601 r->u.usage = openpgp_pk_algo_usage (algo);
2602 r->next = para;
2603 para = r;
2605 else if (err == -1)
2606 return -1;
2607 else
2609 r = get_parameter (para, pSUBKEYUSAGE);
2610 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2612 log_error ("%s:%d: specified Subkey-Usage not allowed"
2613 " for algo %d\n", fname, r->lnr, algo);
2614 return -1;
2620 if( get_parameter_value( para, pUSERID ) )
2621 have_user_id=1;
2622 else
2624 /* create the formatted user ID */
2625 s1 = get_parameter_value( para, pNAMEREAL );
2626 s2 = get_parameter_value( para, pNAMECOMMENT );
2627 s3 = get_parameter_value( para, pNAMEEMAIL );
2628 if( s1 || s2 || s3 )
2630 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2631 r = xmalloc_clear( sizeof *r + n + 20 );
2632 r->key = pUSERID;
2633 p = r->u.value;
2634 if( s1 )
2635 p = stpcpy(p, s1 );
2636 if( s2 )
2637 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2638 if( s3 )
2639 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2640 r->next = para;
2641 para = r;
2642 have_user_id=1;
2646 if(!have_user_id)
2648 log_error("%s: no User-ID specified\n",fname);
2649 return -1;
2652 /* Set preferences, if any. */
2653 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2655 /* Set keyserver, if any. */
2656 s1=get_parameter_value( para, pKEYSERVER );
2657 if(s1)
2659 struct keyserver_spec *spec;
2661 spec=parse_keyserver_uri(s1,1,NULL,0);
2662 if(spec)
2664 free_keyserver_spec(spec);
2665 opt.def_keyserver_url=s1;
2667 else
2669 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2670 return -1;
2674 /* Set revoker, if any. */
2675 if (parse_revocation_key (fname, para, pREVOKER))
2676 return -1;
2678 /* Make DEK and S2K from the Passphrase. */
2679 if (outctrl->ask_passphrase)
2681 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2682 feature is required so that GUIs are able to do a key
2683 creation but have gpg-agent ask for the passphrase. */
2684 int canceled = 0;
2685 STRING2KEY *s2k;
2686 DEK *dek;
2688 dek = do_ask_passphrase (&s2k, 0, &canceled);
2689 if (dek)
2691 r = xmalloc_clear( sizeof *r );
2692 r->key = pPASSPHRASE_DEK;
2693 r->u.dek = dek;
2694 r->next = para;
2695 para = r;
2696 r = xmalloc_clear( sizeof *r );
2697 r->key = pPASSPHRASE_S2K;
2698 r->u.s2k = s2k;
2699 r->next = para;
2700 para = r;
2703 if (canceled)
2705 log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
2706 return -1;
2709 else
2711 r = get_parameter( para, pPASSPHRASE );
2712 if ( r && *r->u.value )
2714 /* We have a plain text passphrase - create a DEK from it.
2715 * It is a little bit ridiculous to keep it in secure memory
2716 * but because we do this always, why not here. */
2717 STRING2KEY *s2k;
2718 DEK *dek;
2720 s2k = xmalloc_secure ( sizeof *s2k );
2721 s2k->mode = opt.s2k_mode;
2722 s2k->hash_algo = S2K_DIGEST_ALGO;
2723 set_next_passphrase ( r->u.value );
2724 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2725 NULL, NULL);
2726 set_next_passphrase (NULL );
2727 assert (dek);
2728 memset (r->u.value, 0, strlen(r->u.value));
2730 r = xmalloc_clear (sizeof *r);
2731 r->key = pPASSPHRASE_S2K;
2732 r->u.s2k = s2k;
2733 r->next = para;
2734 para = r;
2735 r = xmalloc_clear (sizeof *r);
2736 r->key = pPASSPHRASE_DEK;
2737 r->u.dek = dek;
2738 r->next = para;
2739 para = r;
2743 /* Make KEYCREATIONDATE from Creation-Date. */
2744 r = get_parameter (para, pCREATIONDATE);
2745 if (r && *r->u.value)
2747 u32 seconds;
2749 seconds = parse_creation_string (r->u.value);
2750 if (!seconds)
2752 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2753 return -1;
2755 r->u.creation = seconds;
2756 r->key = pKEYCREATIONDATE; /* Change that entry. */
2759 /* Make KEYEXPIRE from Expire-Date. */
2760 r = get_parameter( para, pEXPIREDATE );
2761 if( r && *r->u.value )
2763 u32 seconds;
2765 seconds = parse_expire_string( r->u.value );
2766 if( seconds == (u32)-1 )
2768 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2769 return -1;
2771 r->u.expire = seconds;
2772 r->key = pKEYEXPIRE; /* change hat entry */
2773 /* also set it for the subkey */
2774 r = xmalloc_clear( sizeof *r + 20 );
2775 r->key = pSUBKEYEXPIRE;
2776 r->u.expire = seconds;
2777 r->next = para;
2778 para = r;
2781 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2782 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2783 return -1;
2786 do_generate_keypair( para, outctrl, card );
2787 return 0;
2791 /****************
2792 * Kludge to allow non interactive key generation controlled
2793 * by a parameter file.
2794 * Note, that string parameters are expected to be in UTF-8
2796 static void
2797 read_parameter_file( const char *fname )
2799 static struct { const char *name;
2800 enum para_name key;
2801 } keywords[] = {
2802 { "Key-Type", pKEYTYPE},
2803 { "Key-Length", pKEYLENGTH },
2804 { "Key-Usage", pKEYUSAGE },
2805 { "Subkey-Type", pSUBKEYTYPE },
2806 { "Subkey-Length", pSUBKEYLENGTH },
2807 { "Subkey-Usage", pSUBKEYUSAGE },
2808 { "Name-Real", pNAMEREAL },
2809 { "Name-Email", pNAMEEMAIL },
2810 { "Name-Comment", pNAMECOMMENT },
2811 { "Expire-Date", pEXPIREDATE },
2812 { "Creation-Date", pCREATIONDATE },
2813 { "Passphrase", pPASSPHRASE },
2814 { "Preferences", pPREFERENCES },
2815 { "Revoker", pREVOKER },
2816 { "Handle", pHANDLE },
2817 { "Keyserver", pKEYSERVER },
2818 { NULL, 0 }
2820 IOBUF fp;
2821 byte *line;
2822 unsigned int maxlen, nline;
2823 char *p;
2824 int lnr;
2825 const char *err = NULL;
2826 struct para_data_s *para, *r;
2827 int i;
2828 struct output_control_s outctrl;
2830 memset( &outctrl, 0, sizeof( outctrl ) );
2831 outctrl.pub.afx = new_armor_context ();
2832 outctrl.sec.afx = new_armor_context ();
2834 if( !fname || !*fname)
2835 fname = "-";
2837 fp = iobuf_open (fname);
2838 if (fp && is_secured_file (iobuf_get_fd (fp)))
2840 iobuf_close (fp);
2841 fp = NULL;
2842 errno = EPERM;
2844 if (!fp) {
2845 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2846 return;
2848 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2850 lnr = 0;
2851 err = NULL;
2852 para = NULL;
2853 maxlen = 1024;
2854 line = NULL;
2855 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2856 char *keyword, *value;
2858 lnr++;
2859 if( !maxlen ) {
2860 err = "line too long";
2861 break;
2863 for( p = line; isspace(*(byte*)p); p++ )
2865 if( !*p || *p == '#' )
2866 continue;
2867 keyword = p;
2868 if( *keyword == '%' ) {
2869 for( ; !isspace(*(byte*)p); p++ )
2871 if( *p )
2872 *p++ = 0;
2873 for( ; isspace(*(byte*)p); p++ )
2875 value = p;
2876 trim_trailing_ws( value, strlen(value) );
2877 if( !ascii_strcasecmp( keyword, "%echo" ) )
2878 log_info("%s\n", value );
2879 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2880 outctrl.dryrun = 1;
2881 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
2882 outctrl.ask_passphrase = 1;
2883 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
2884 outctrl.ask_passphrase = 0;
2885 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2886 outctrl.lnr = lnr;
2887 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2888 print_status_key_not_created
2889 (get_parameter_value (para, pHANDLE));
2890 release_parameter_list( para );
2891 para = NULL;
2893 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2894 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2895 ; /* still the same file - ignore it */
2896 else {
2897 xfree( outctrl.pub.newfname );
2898 outctrl.pub.newfname = xstrdup( value );
2899 outctrl.use_files = 1;
2902 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2903 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2904 ; /* still the same file - ignore it */
2905 else {
2906 xfree( outctrl.sec.newfname );
2907 outctrl.sec.newfname = xstrdup( value );
2908 outctrl.use_files = 1;
2911 else
2912 log_info("skipping control `%s' (%s)\n", keyword, value );
2915 continue;
2919 if( !(p = strchr( p, ':' )) || p == keyword ) {
2920 err = "missing colon";
2921 break;
2923 if( *p )
2924 *p++ = 0;
2925 for( ; isspace(*(byte*)p); p++ )
2927 if( !*p ) {
2928 err = "missing argument";
2929 break;
2931 value = p;
2932 trim_trailing_ws( value, strlen(value) );
2934 for(i=0; keywords[i].name; i++ ) {
2935 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2936 break;
2938 if( !keywords[i].name ) {
2939 err = "unknown keyword";
2940 break;
2942 if( keywords[i].key != pKEYTYPE && !para ) {
2943 err = "parameter block does not start with \"Key-Type\"";
2944 break;
2947 if( keywords[i].key == pKEYTYPE && para ) {
2948 outctrl.lnr = lnr;
2949 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2950 print_status_key_not_created
2951 (get_parameter_value (para, pHANDLE));
2952 release_parameter_list( para );
2953 para = NULL;
2955 else {
2956 for( r = para; r; r = r->next ) {
2957 if( r->key == keywords[i].key )
2958 break;
2960 if( r ) {
2961 err = "duplicate keyword";
2962 break;
2965 r = xmalloc_clear( sizeof *r + strlen( value ) );
2966 r->lnr = lnr;
2967 r->key = keywords[i].key;
2968 strcpy( r->u.value, value );
2969 r->next = para;
2970 para = r;
2972 if( err )
2973 log_error("%s:%d: %s\n", fname, lnr, err );
2974 else if( iobuf_error (fp) ) {
2975 log_error("%s:%d: read error\n", fname, lnr);
2977 else if( para ) {
2978 outctrl.lnr = lnr;
2979 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2980 print_status_key_not_created (get_parameter_value (para, pHANDLE));
2983 if( outctrl.use_files ) { /* close open streams */
2984 iobuf_close( outctrl.pub.stream );
2985 iobuf_close( outctrl.sec.stream );
2987 /* Must invalidate that ugly cache to actually close it. */
2988 if (outctrl.pub.fname)
2989 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
2990 if (outctrl.sec.fname)
2991 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
2993 xfree( outctrl.pub.fname );
2994 xfree( outctrl.pub.newfname );
2995 xfree( outctrl.sec.fname );
2996 xfree( outctrl.sec.newfname );
2999 release_parameter_list( para );
3000 iobuf_close (fp);
3001 release_armor_context (outctrl.pub.afx);
3002 release_armor_context (outctrl.sec.afx);
3007 * Generate a keypair (fname is only used in batch mode) If
3008 * CARD_SERIALNO is not NULL the function will create the keys on an
3009 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
3010 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
3011 * generate in software, imported to the card and a backup file
3012 * written to directory given by this argument .
3014 void
3015 generate_keypair (const char *fname, const char *card_serialno,
3016 const char *backup_encryption_dir)
3018 unsigned int nbits;
3019 char *uid = NULL;
3020 DEK *dek;
3021 STRING2KEY *s2k;
3022 int algo;
3023 unsigned int use;
3024 int both = 0;
3025 u32 expire;
3026 struct para_data_s *para = NULL;
3027 struct para_data_s *r;
3028 struct output_control_s outctrl;
3029 int canceled;
3031 memset( &outctrl, 0, sizeof( outctrl ) );
3033 if (opt.batch && card_serialno)
3035 /* We don't yet support unattended key generation. */
3036 log_error (_("can't do this in batch mode\n"));
3037 return;
3040 if (opt.batch)
3042 read_parameter_file( fname );
3043 return;
3046 if (card_serialno)
3048 #ifdef ENABLE_CARD_SUPPORT
3049 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
3050 r->key = pSERIALNO;
3051 strcpy( r->u.value, card_serialno);
3052 r->next = para;
3053 para = r;
3055 algo = PUBKEY_ALGO_RSA;
3057 r = xcalloc (1, sizeof *r + 20 );
3058 r->key = pKEYTYPE;
3059 sprintf( r->u.value, "%d", algo );
3060 r->next = para;
3061 para = r;
3062 r = xcalloc (1, sizeof *r + 20 );
3063 r->key = pKEYUSAGE;
3064 strcpy (r->u.value, "sign");
3065 r->next = para;
3066 para = r;
3068 r = xcalloc (1, sizeof *r + 20 );
3069 r->key = pSUBKEYTYPE;
3070 sprintf( r->u.value, "%d", algo );
3071 r->next = para;
3072 para = r;
3073 r = xcalloc (1, sizeof *r + 20 );
3074 r->key = pSUBKEYUSAGE;
3075 strcpy (r->u.value, "encrypt");
3076 r->next = para;
3077 para = r;
3079 r = xcalloc (1, sizeof *r + 20 );
3080 r->key = pAUTHKEYTYPE;
3081 sprintf( r->u.value, "%d", algo );
3082 r->next = para;
3083 para = r;
3085 if (backup_encryption_dir)
3087 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
3088 r->key = pBACKUPENCDIR;
3089 strcpy (r->u.value, backup_encryption_dir);
3090 r->next = para;
3091 para = r;
3093 #endif /*ENABLE_CARD_SUPPORT*/
3095 else
3097 int subkey_algo;
3099 algo = ask_algo (0, &subkey_algo, &use);
3100 if (subkey_algo)
3102 /* Create primary and subkey at once. */
3103 both = 1;
3104 r = xmalloc_clear( sizeof *r + 20 );
3105 r->key = pKEYTYPE;
3106 sprintf( r->u.value, "%d", algo );
3107 r->next = para;
3108 para = r;
3109 nbits = ask_keysize (algo, 0);
3110 r = xmalloc_clear( sizeof *r + 20 );
3111 r->key = pKEYLENGTH;
3112 sprintf( r->u.value, "%u", nbits);
3113 r->next = para;
3114 para = r;
3115 r = xmalloc_clear( sizeof *r + 20 );
3116 r->key = pKEYUSAGE;
3117 strcpy( r->u.value, "sign" );
3118 r->next = para;
3119 para = r;
3121 r = xmalloc_clear( sizeof *r + 20 );
3122 r->key = pSUBKEYTYPE;
3123 sprintf( r->u.value, "%d", subkey_algo);
3124 r->next = para;
3125 para = r;
3126 r = xmalloc_clear( sizeof *r + 20 );
3127 r->key = pSUBKEYUSAGE;
3128 strcpy( r->u.value, "encrypt" );
3129 r->next = para;
3130 para = r;
3132 else
3134 r = xmalloc_clear( sizeof *r + 20 );
3135 r->key = pKEYTYPE;
3136 sprintf( r->u.value, "%d", algo );
3137 r->next = para;
3138 para = r;
3140 if (use)
3142 r = xmalloc_clear( sizeof *r + 25 );
3143 r->key = pKEYUSAGE;
3144 sprintf( r->u.value, "%s%s%s",
3145 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3146 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3147 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3148 r->next = para;
3149 para = r;
3151 nbits = 0;
3154 nbits = ask_keysize (both? subkey_algo : algo, nbits);
3155 r = xmalloc_clear( sizeof *r + 20 );
3156 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3157 sprintf( r->u.value, "%u", nbits);
3158 r->next = para;
3159 para = r;
3162 expire = ask_expire_interval(0,NULL);
3163 r = xmalloc_clear( sizeof *r + 20 );
3164 r->key = pKEYEXPIRE;
3165 r->u.expire = expire;
3166 r->next = para;
3167 para = r;
3168 r = xmalloc_clear( sizeof *r + 20 );
3169 r->key = pSUBKEYEXPIRE;
3170 r->u.expire = expire;
3171 r->next = para;
3172 para = r;
3174 uid = ask_user_id (0, NULL);
3175 if( !uid )
3177 log_error(_("Key generation canceled.\n"));
3178 release_parameter_list( para );
3179 return;
3181 r = xmalloc_clear( sizeof *r + strlen(uid) );
3182 r->key = pUSERID;
3183 strcpy( r->u.value, uid );
3184 r->next = para;
3185 para = r;
3187 canceled = 0;
3188 dek = card_serialno? NULL : do_ask_passphrase (&s2k, 0, &canceled);
3189 if( dek )
3191 r = xmalloc_clear( sizeof *r );
3192 r->key = pPASSPHRASE_DEK;
3193 r->u.dek = dek;
3194 r->next = para;
3195 para = r;
3196 r = xmalloc_clear( sizeof *r );
3197 r->key = pPASSPHRASE_S2K;
3198 r->u.s2k = s2k;
3199 r->next = para;
3200 para = r;
3203 if (canceled)
3204 log_error (_("Key generation canceled.\n"));
3205 else
3206 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3207 release_parameter_list( para );
3211 #ifdef ENABLE_CARD_SUPPORT
3212 /* Generate a raw key and return it as a secret key packet. The
3213 function will ask for the passphrase and return a protected as well
3214 as an unprotected copy of a new secret key packet. 0 is returned
3215 on success and the caller must then free the returned values. */
3216 static int
3217 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3218 PKT_secret_key **r_sk_unprotected,
3219 PKT_secret_key **r_sk_protected)
3221 int rc;
3222 DEK *dek = NULL;
3223 STRING2KEY *s2k = NULL;
3224 PKT_secret_key *sk = NULL;
3225 int i;
3226 size_t nskey, npkey;
3227 gcry_sexp_t s_parms, s_key;
3228 int canceled;
3230 npkey = pubkey_get_npkey (algo);
3231 nskey = pubkey_get_nskey (algo);
3232 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3234 if (nbits < 512)
3236 nbits = 512;
3237 log_info (_("keysize invalid; using %u bits\n"), nbits );
3240 if ((nbits % 32))
3242 nbits = ((nbits + 31) / 32) * 32;
3243 log_info(_("keysize rounded up to %u bits\n"), nbits );
3246 dek = do_ask_passphrase (&s2k, 1, &canceled);
3247 if (canceled)
3249 rc = gpg_error (GPG_ERR_CANCELED);
3250 goto leave;
3253 sk = xmalloc_clear (sizeof *sk);
3254 sk->timestamp = created_at;
3255 sk->version = 4;
3256 sk->pubkey_algo = algo;
3258 if ( !is_RSA (algo) )
3260 log_error ("only RSA is supported for offline generated keys\n");
3261 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3262 goto leave;
3264 rc = gcry_sexp_build (&s_parms, NULL,
3265 "(genkey(rsa(nbits %d)))",
3266 (int)nbits);
3267 if (rc)
3268 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3269 rc = gcry_pk_genkey (&s_key, s_parms);
3270 gcry_sexp_release (s_parms);
3271 if (rc)
3273 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3274 goto leave;
3276 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3277 gcry_sexp_release (s_key);
3278 if (rc)
3280 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3281 goto leave;
3284 for (i=npkey; i < nskey; i++)
3285 sk->csum += checksum_mpi (sk->skey[i]);
3287 if (r_sk_unprotected)
3288 *r_sk_unprotected = copy_secret_key (NULL, sk);
3290 rc = genhelp_protect (dek, s2k, sk);
3291 if (rc)
3292 goto leave;
3294 if (r_sk_protected)
3296 *r_sk_protected = sk;
3297 sk = NULL;
3300 leave:
3301 if (sk)
3302 free_secret_key (sk);
3303 xfree (dek);
3304 xfree (s2k);
3305 return rc;
3307 #endif /* ENABLE_CARD_SUPPORT */
3309 /* Create and delete a dummy packet to start off a list of kbnodes. */
3310 static void
3311 start_tree(KBNODE *tree)
3313 PACKET *pkt;
3315 pkt=xmalloc_clear(sizeof(*pkt));
3316 pkt->pkttype=PKT_NONE;
3317 *tree=new_kbnode(pkt);
3318 delete_kbnode(*tree);
3322 static void
3323 do_generate_keypair (struct para_data_s *para,
3324 struct output_control_s *outctrl, int card)
3326 KBNODE pub_root = NULL;
3327 KBNODE sec_root = NULL;
3328 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3329 const char *s;
3330 struct revocation_key *revkey;
3331 int rc;
3332 int did_sub = 0;
3333 u32 timestamp;
3335 if( outctrl->dryrun )
3337 log_info("dry-run mode - key generation skipped\n");
3338 return;
3341 if ( outctrl->use_files )
3343 if ( outctrl->pub.newfname )
3345 iobuf_close(outctrl->pub.stream);
3346 outctrl->pub.stream = NULL;
3347 if (outctrl->pub.fname)
3348 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3349 xfree( outctrl->pub.fname );
3350 outctrl->pub.fname = outctrl->pub.newfname;
3351 outctrl->pub.newfname = NULL;
3353 if (is_secured_filename (outctrl->pub.fname) )
3355 outctrl->pub.stream = NULL;
3356 errno = EPERM;
3358 else
3359 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3360 if (!outctrl->pub.stream)
3362 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3363 strerror(errno) );
3364 return;
3366 if (opt.armor)
3368 outctrl->pub.afx->what = 1;
3369 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3372 if (outctrl->sec.newfname)
3374 mode_t oldmask;
3376 iobuf_close(outctrl->sec.stream);
3377 outctrl->sec.stream = NULL;
3378 if (outctrl->sec.fname)
3379 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3380 xfree( outctrl->sec.fname );
3381 outctrl->sec.fname = outctrl->sec.newfname;
3382 outctrl->sec.newfname = NULL;
3384 oldmask = umask (077);
3385 if (is_secured_filename (outctrl->sec.fname) )
3387 outctrl->sec.stream = NULL;
3388 errno = EPERM;
3390 else
3391 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3392 umask (oldmask);
3393 if (!outctrl->sec.stream)
3395 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3396 strerror(errno) );
3397 return;
3399 if (opt.armor)
3401 outctrl->sec.afx->what = 5;
3402 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3405 assert( outctrl->pub.stream );
3406 assert( outctrl->sec.stream );
3407 if (opt.verbose)
3409 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3410 if (card)
3411 log_info (_("writing secret key stub to `%s'\n"),
3412 outctrl->sec.fname);
3413 else
3414 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3419 /* We create the packets as a tree of kbnodes. Because the
3420 structure we create is known in advance we simply generate a
3421 linked list. The first packet is a dummy packet which we flag as
3422 deleted. The very first packet must always be a KEY packet. */
3424 start_tree (&pub_root);
3425 start_tree (&sec_root);
3427 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3428 if (!timestamp)
3429 timestamp = make_timestamp ();
3431 /* Note that, depending on the backend (i.e. the used scdaemon
3432 version), the card key generation may update TIMESTAMP for each
3433 key. Thus we need to pass TIMESTAMP to all signing function to
3434 make sure that the binding signature is done using the timestamp
3435 of the corresponding (sub)key and not that of the primary key.
3436 An alternative implementation could tell the signing function the
3437 node of the subkey but that is more work than just to pass the
3438 current timestamp. */
3440 if (!card)
3442 rc = do_create (get_parameter_algo( para, pKEYTYPE ),
3443 get_parameter_uint( para, pKEYLENGTH ),
3444 pub_root, sec_root,
3445 get_parameter_dek( para, pPASSPHRASE_DEK ),
3446 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3447 &pri_sk,
3448 timestamp,
3449 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3451 else
3453 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3454 &timestamp,
3455 get_parameter_u32 (para, pKEYEXPIRE), para);
3456 if (!rc)
3458 pri_sk = sec_root->next->pkt->pkt.secret_key;
3459 assert (pri_sk);
3463 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3465 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3466 if (!rc)
3467 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3470 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3472 write_uid (pub_root, s );
3473 write_uid (sec_root, s );
3475 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3476 get_parameter_uint (para, pKEYUSAGE), timestamp);
3479 /* Write the auth key to the card before the encryption key. This
3480 is a partial workaround for a PGP bug (as of this writing, all
3481 versions including 8.1), that causes it to try and encrypt to
3482 the most recent subkey regardless of whether that subkey is
3483 actually an encryption type. In this case, the auth key is an
3484 RSA key so it succeeds. */
3486 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3488 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3489 &timestamp,
3490 get_parameter_u32 (para, pKEYEXPIRE), para);
3492 if (!rc)
3493 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3494 PUBKEY_USAGE_AUTH, timestamp);
3495 if (!rc)
3496 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3497 PUBKEY_USAGE_AUTH, timestamp);
3500 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3502 if (!card)
3504 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
3505 get_parameter_uint( para, pSUBKEYLENGTH ),
3506 pub_root, sec_root,
3507 get_parameter_dek( para, pPASSPHRASE_DEK ),
3508 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3509 &sub_sk,
3510 timestamp,
3511 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3513 else
3515 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3517 /* A backup of the encryption key has been requested.
3518 Generate the key in software and import it then to
3519 the card. Write a backup file. */
3520 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3521 pub_root, sec_root,
3522 timestamp,
3523 get_parameter_u32 (para,
3524 pKEYEXPIRE),
3525 para, s);
3527 else
3529 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3530 NULL,
3531 &timestamp,
3532 get_parameter_u32 (para, pKEYEXPIRE), para);
3536 if( !rc )
3537 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3538 get_parameter_uint (para, pSUBKEYUSAGE),
3539 timestamp);
3540 if( !rc )
3541 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3542 get_parameter_uint (para, pSUBKEYUSAGE),
3543 timestamp);
3544 did_sub = 1;
3547 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3549 rc = write_keyblock( outctrl->pub.stream, pub_root );
3550 if (rc)
3551 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3552 if (!rc)
3554 rc = write_keyblock( outctrl->sec.stream, sec_root );
3555 if(rc)
3556 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3559 else if (!rc) /* Write to the standard keyrings. */
3561 KEYDB_HANDLE pub_hd = keydb_new (0);
3562 KEYDB_HANDLE sec_hd = keydb_new (1);
3564 rc = keydb_locate_writable (pub_hd, NULL);
3565 if (rc)
3566 log_error (_("no writable public keyring found: %s\n"),
3567 g10_errstr (rc));
3569 if (!rc)
3571 rc = keydb_locate_writable (sec_hd, NULL);
3572 if (rc)
3573 log_error (_("no writable secret keyring found: %s\n"),
3574 g10_errstr (rc));
3577 if (!rc && opt.verbose)
3579 log_info (_("writing public key to `%s'\n"),
3580 keydb_get_resource_name (pub_hd));
3581 if (card)
3582 log_info (_("writing secret key stub to `%s'\n"),
3583 keydb_get_resource_name (sec_hd));
3584 else
3585 log_info (_("writing secret key to `%s'\n"),
3586 keydb_get_resource_name (sec_hd));
3589 if (!rc)
3591 rc = keydb_insert_keyblock (pub_hd, pub_root);
3592 if (rc)
3593 log_error (_("error writing public keyring `%s': %s\n"),
3594 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3597 if (!rc)
3599 rc = keydb_insert_keyblock (sec_hd, sec_root);
3600 if (rc)
3601 log_error (_("error writing secret keyring `%s': %s\n"),
3602 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3605 keydb_release (pub_hd);
3606 keydb_release (sec_hd);
3608 if (!rc)
3610 int no_enc_rsa;
3611 PKT_public_key *pk;
3613 no_enc_rsa = (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
3614 && get_parameter_uint (para, pKEYUSAGE)
3615 && !((get_parameter_uint (para, pKEYUSAGE)
3616 & PUBKEY_USAGE_ENC)) );
3618 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3620 keyid_from_pk(pk,pk->main_keyid);
3621 register_trusted_keyid(pk->main_keyid);
3623 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3624 | TRUST_ULTIMATE ));
3626 if (!opt.batch)
3628 tty_printf (_("public and secret key created and signed.\n") );
3629 tty_printf ("\n");
3630 list_keyblock(pub_root,0,1,NULL);
3634 if (!opt.batch
3635 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
3636 || no_enc_rsa )
3637 && !get_parameter (para, pSUBKEYTYPE) )
3639 tty_printf(_("Note that this key cannot be used for "
3640 "encryption. You may want to use\n"
3641 "the command \"--edit-key\" to generate a "
3642 "subkey for this purpose.\n") );
3647 if (rc)
3649 if (opt.batch)
3650 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3651 else
3652 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3653 write_status_error (card? "card_key_generate":"key_generate", rc);
3654 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3656 else
3658 PKT_public_key *pk = find_kbnode (pub_root,
3659 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3660 print_status_key_created (did_sub? 'B':'P', pk,
3661 get_parameter_value (para, pHANDLE));
3663 release_kbnode( pub_root );
3664 release_kbnode( sec_root );
3666 if (pri_sk && !card) /* The unprotected secret key unless we */
3667 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3668 if (sub_sk)
3669 free_secret_key(sub_sk);
3673 /* Add a new subkey to an existing key. Returns true if a new key has
3674 been generated and put into the keyblocks. */
3676 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3678 int okay=0, rc=0;
3679 KBNODE node;
3680 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3681 int algo;
3682 unsigned int use;
3683 u32 expire;
3684 unsigned nbits;
3685 char *passphrase = NULL;
3686 DEK *dek = NULL;
3687 STRING2KEY *s2k = NULL;
3688 u32 cur_time;
3689 int ask_pass = 0;
3690 int canceled;
3692 /* Break out the primary secret key. */
3693 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3694 if( !node )
3696 log_error ("Oops; secret key not found anymore!\n");
3697 goto leave;
3700 /* Make a copy of the sk to keep the protected one in the keyblock. */
3701 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3703 cur_time = make_timestamp();
3705 if (pri_sk->timestamp > cur_time)
3707 ulong d = pri_sk->timestamp - cur_time;
3708 log_info ( d==1 ? _("key has been created %lu second "
3709 "in future (time warp or clock problem)\n")
3710 : _("key has been created %lu seconds "
3711 "in future (time warp or clock problem)\n"), d );
3712 if (!opt.ignore_time_conflict)
3714 rc = G10ERR_TIME_CONFLICT;
3715 goto leave;
3719 if (pri_sk->version < 4)
3721 log_info (_("NOTE: creating subkeys for v3 keys "
3722 "is not OpenPGP compliant\n"));
3723 goto leave;
3726 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3728 tty_printf (_("Secret parts of primary key are not available.\n"));
3729 rc = G10ERR_NO_SECKEY;
3730 goto leave;
3734 /* Unprotect to get the passphrase. */
3735 switch (is_secret_key_protected (pri_sk) )
3737 case -1:
3738 rc = G10ERR_PUBKEY_ALGO;
3739 break;
3740 case 0:
3741 tty_printf (_("This key is not protected.\n"));
3742 break;
3743 case -2:
3744 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3745 ask_pass = 1;
3746 break;
3747 default:
3748 tty_printf (_("Key is protected.\n"));
3749 rc = check_secret_key ( pri_sk, 0 );
3750 if (!rc)
3751 passphrase = get_last_passphrase();
3752 break;
3754 if (rc)
3755 goto leave;
3757 algo = ask_algo (1, NULL, &use);
3758 assert (algo);
3759 nbits = ask_keysize (algo, 0);
3760 expire = ask_expire_interval (0, NULL);
3761 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3762 _("Really create? (y/N) ")))
3763 goto leave;
3765 canceled = 0;
3766 if (ask_pass)
3767 dek = do_ask_passphrase (&s2k, 0, &canceled);
3768 else if (passphrase)
3770 s2k = xmalloc_secure ( sizeof *s2k );
3771 s2k->mode = opt.s2k_mode;
3772 s2k->hash_algo = S2K_DIGEST_ALGO;
3773 set_next_passphrase ( passphrase );
3774 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3775 NULL, NULL );
3778 if (canceled)
3779 rc = GPG_ERR_CANCELED;
3781 if (!rc)
3782 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3783 dek, s2k, &sub_sk, cur_time, expire, 1 );
3784 if (!rc)
3785 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3786 use, cur_time);
3787 if (!rc)
3788 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3789 use, cur_time);
3790 if (!rc)
3792 okay = 1;
3793 write_status_text (STATUS_KEY_CREATED, "S");
3796 leave:
3797 if (rc)
3798 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3799 xfree (passphrase);
3800 xfree (dek);
3801 xfree (s2k);
3802 /* Release the copy of the (now unprotected) secret keys. */
3803 if (pri_sk)
3804 free_secret_key (pri_sk);
3805 if (sub_sk)
3806 free_secret_key (sub_sk);
3807 set_next_passphrase (NULL);
3808 return okay;
3812 #ifdef ENABLE_CARD_SUPPORT
3813 /* Generate a subkey on a card. */
3815 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3816 int keyno, const char *serialno)
3818 int okay=0, rc=0;
3819 KBNODE node;
3820 PKT_secret_key *pri_sk = NULL, *sub_sk;
3821 int algo;
3822 unsigned int use;
3823 u32 expire;
3824 char *passphrase = NULL;
3825 u32 cur_time;
3826 struct para_data_s *para = NULL;
3828 assert (keyno >= 1 && keyno <= 3);
3830 para = xcalloc (1, sizeof *para + strlen (serialno) );
3831 para->key = pSERIALNO;
3832 strcpy (para->u.value, serialno);
3834 /* Break out the primary secret key */
3835 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3836 if (!node)
3838 log_error("Oops; secret key not found anymore!\n");
3839 goto leave;
3842 /* Make a copy of the sk to keep the protected one in the keyblock */
3843 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3845 cur_time = make_timestamp();
3846 if (pri_sk->timestamp > cur_time)
3848 ulong d = pri_sk->timestamp - cur_time;
3849 log_info (d==1 ? _("key has been created %lu second "
3850 "in future (time warp or clock problem)\n")
3851 : _("key has been created %lu seconds "
3852 "in future (time warp or clock problem)\n"), d );
3853 if (!opt.ignore_time_conflict)
3855 rc = G10ERR_TIME_CONFLICT;
3856 goto leave;
3860 if (pri_sk->version < 4)
3862 log_info (_("NOTE: creating subkeys for v3 keys "
3863 "is not OpenPGP compliant\n"));
3864 goto leave;
3867 /* Unprotect to get the passphrase. */
3868 switch( is_secret_key_protected (pri_sk) )
3870 case -1:
3871 rc = G10ERR_PUBKEY_ALGO;
3872 break;
3873 case 0:
3874 tty_printf("This key is not protected.\n");
3875 break;
3876 default:
3877 tty_printf("Key is protected.\n");
3878 rc = check_secret_key( pri_sk, 0 );
3879 if (!rc)
3880 passphrase = get_last_passphrase();
3881 break;
3883 if (rc)
3884 goto leave;
3886 algo = PUBKEY_ALGO_RSA;
3887 expire = ask_expire_interval (0,NULL);
3888 if (keyno == 1)
3889 use = PUBKEY_USAGE_SIG;
3890 else if (keyno == 2)
3891 use = PUBKEY_USAGE_ENC;
3892 else
3893 use = PUBKEY_USAGE_AUTH;
3894 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3895 _("Really create? (y/N) ")))
3896 goto leave;
3898 if (passphrase)
3899 set_next_passphrase (passphrase);
3901 /* Note, that depending on the backend, the card key generation may
3902 update CUR_TIME. */
3903 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3904 &sub_sk, &cur_time, expire, para);
3905 if (!rc)
3906 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3907 use, cur_time);
3908 if (!rc)
3909 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3910 use, cur_time);
3911 if (!rc)
3913 okay = 1;
3914 write_status_text (STATUS_KEY_CREATED, "S");
3917 leave:
3918 if (rc)
3919 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3920 xfree (passphrase);
3921 /* Release the copy of the (now unprotected) secret keys. */
3922 if (pri_sk)
3923 free_secret_key (pri_sk);
3924 set_next_passphrase( NULL );
3925 release_parameter_list (para);
3926 return okay;
3928 #endif /* !ENABLE_CARD_SUPPORT */
3932 * Write a keyblock to an output stream
3934 static int
3935 write_keyblock( IOBUF out, KBNODE node )
3937 for( ; node ; node = node->next )
3939 if(!is_deleted_kbnode(node))
3941 int rc = build_packet( out, node->pkt );
3942 if( rc )
3944 log_error("build_packet(%d) failed: %s\n",
3945 node->pkt->pkttype, g10_errstr(rc) );
3946 return rc;
3951 return 0;
3955 /* Note that timestamp is an in/out arg. */
3956 static int
3957 gen_card_key (int algo, int keyno, int is_primary,
3958 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
3959 u32 *timestamp, u32 expireval, struct para_data_s *para)
3961 #ifdef ENABLE_CARD_SUPPORT
3962 int rc;
3963 const char *s;
3964 struct agent_card_genkey_s info;
3965 PACKET *pkt;
3966 PKT_secret_key *sk;
3967 PKT_public_key *pk;
3969 assert (algo == PUBKEY_ALGO_RSA);
3971 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3972 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
3973 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3974 /* { */
3975 /* tty_printf ("\n"); */
3976 /* log_error ("WARNING: key does already exists!\n"); */
3977 /* tty_printf ("\n"); */
3978 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3979 /* _("Replace existing key? "))) */
3980 /* rc = agent_scd_genkey (&info, keyno, 1); */
3981 /* } */
3983 if (rc)
3985 log_error ("key generation failed: %s\n", gpg_strerror (rc));
3986 return rc;
3988 if ( !info.n || !info.e )
3990 log_error ("communication error with SCD\n");
3991 gcry_mpi_release (info.n);
3992 gcry_mpi_release (info.e);
3993 return gpg_error (GPG_ERR_GENERAL);
3996 if (*timestamp != info.created_at)
3997 log_info ("Note that the key does not use the suggested creation date\n");
3998 *timestamp = info.created_at;
4000 pk = xcalloc (1, sizeof *pk );
4001 sk = xcalloc (1, sizeof *sk );
4002 sk->timestamp = pk->timestamp = info.created_at;
4003 sk->version = pk->version = 4;
4004 if (expireval)
4005 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
4006 sk->pubkey_algo = pk->pubkey_algo = algo;
4007 pk->pkey[0] = info.n;
4008 pk->pkey[1] = info.e;
4009 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
4010 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
4011 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
4012 sk->is_protected = 1;
4013 sk->protect.s2k.mode = 1002;
4014 s = get_parameter_value (para, pSERIALNO);
4015 if (s)
4017 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
4018 sk->protect.ivlen++, s += 2)
4019 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
4022 if( ret_sk )
4023 *ret_sk = sk;
4025 pkt = xcalloc (1,sizeof *pkt);
4026 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4027 pkt->pkt.public_key = pk;
4028 add_kbnode(pub_root, new_kbnode( pkt ));
4030 pkt = xcalloc (1,sizeof *pkt);
4031 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4032 pkt->pkt.secret_key = sk;
4033 add_kbnode(sec_root, new_kbnode( pkt ));
4035 return 0;
4036 #else
4037 return -1;
4038 #endif /*!ENABLE_CARD_SUPPORT*/
4043 static int
4044 gen_card_key_with_backup (int algo, int keyno, int is_primary,
4045 KBNODE pub_root, KBNODE sec_root,
4046 u32 timestamp,
4047 u32 expireval, struct para_data_s *para,
4048 const char *backup_dir)
4050 #ifdef ENABLE_CARD_SUPPORT
4051 int rc;
4052 const char *s;
4053 PACKET *pkt;
4054 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
4055 PKT_public_key *pk;
4056 size_t n;
4057 int i;
4058 unsigned int nbits;
4060 /* Get the size of the key directly from the card. */
4062 struct agent_card_info_s info;
4064 memset (&info, 0, sizeof info);
4065 if (!agent_scd_getattr ("KEY-ATTR", &info)
4066 && info.key_attr[1].algo)
4067 nbits = info.key_attr[1].nbits;
4068 else
4069 nbits = 1024; /* All pre-v2.0 cards. */
4070 agent_release_card_info (&info);
4073 /* Create a key of this size in memory. */
4074 rc = generate_raw_key (algo, nbits, timestamp,
4075 &sk_unprotected, &sk_protected);
4076 if (rc)
4077 return rc;
4079 /* Store the key to the card. */
4080 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
4081 if (rc)
4083 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
4084 free_secret_key (sk_unprotected);
4085 free_secret_key (sk_protected);
4086 write_status_error ("save_key_to_card", rc);
4087 return rc;
4090 /* Get rid of the secret key parameters and store the serial numer. */
4091 sk = sk_unprotected;
4092 n = pubkey_get_nskey (sk->pubkey_algo);
4093 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
4095 gcry_mpi_release (sk->skey[i]);
4096 sk->skey[i] = NULL;
4098 i = pubkey_get_npkey (sk->pubkey_algo);
4099 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
4100 sk->is_protected = 1;
4101 sk->protect.s2k.mode = 1002;
4102 s = get_parameter_value (para, pSERIALNO);
4103 assert (s);
4104 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
4105 sk->protect.ivlen++, s += 2)
4106 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
4108 /* Now write the *protected* secret key to the file. */
4110 char name_buffer[50];
4111 char *fname;
4112 IOBUF fp;
4113 mode_t oldmask;
4115 keyid_from_sk (sk, NULL);
4116 snprintf (name_buffer, sizeof name_buffer, "sk_%08lX%08lX.gpg",
4117 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
4119 fname = make_filename (backup_dir, name_buffer, NULL);
4120 oldmask = umask (077);
4121 if (is_secured_filename (fname))
4123 fp = NULL;
4124 errno = EPERM;
4126 else
4127 fp = iobuf_create (fname);
4128 umask (oldmask);
4129 if (!fp)
4131 rc = gpg_error_from_syserror ();
4132 log_error (_("can't create backup file `%s': %s\n"),
4133 fname, strerror(errno) );
4134 xfree (fname);
4135 free_secret_key (sk_unprotected);
4136 free_secret_key (sk_protected);
4137 return rc;
4140 pkt = xcalloc (1, sizeof *pkt);
4141 pkt->pkttype = PKT_SECRET_KEY;
4142 pkt->pkt.secret_key = sk_protected;
4143 sk_protected = NULL;
4145 rc = build_packet (fp, pkt);
4146 if (rc)
4148 log_error("build packet failed: %s\n", g10_errstr(rc) );
4149 iobuf_cancel (fp);
4151 else
4153 unsigned char array[MAX_FINGERPRINT_LEN];
4154 char *fprbuf, *p;
4156 iobuf_close (fp);
4157 iobuf_ioctl (NULL, 2, 0, (char*)fname);
4158 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
4160 fingerprint_from_sk (sk, array, &n);
4161 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4162 for (i=0; i < n ; i++, p += 2)
4163 sprintf (p, "%02X", array[i]);
4164 *p++ = ' ';
4165 *p = 0;
4167 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4168 fprbuf,
4169 fname, strlen (fname),
4171 xfree (fprbuf);
4173 free_packet (pkt);
4174 xfree (pkt);
4175 xfree (fname);
4176 if (rc)
4178 free_secret_key (sk_unprotected);
4179 return rc;
4183 /* Create the public key from the secret key. */
4184 pk = xcalloc (1, sizeof *pk );
4185 pk->timestamp = sk->timestamp;
4186 pk->version = sk->version;
4187 if (expireval)
4188 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4189 pk->pubkey_algo = sk->pubkey_algo;
4190 n = pubkey_get_npkey (sk->pubkey_algo);
4191 for (i=0; i < n; i++)
4192 pk->pkey[i] = mpi_copy (sk->skey[i]);
4194 /* Build packets and add them to the node lists. */
4195 pkt = xcalloc (1,sizeof *pkt);
4196 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4197 pkt->pkt.public_key = pk;
4198 add_kbnode(pub_root, new_kbnode( pkt ));
4200 pkt = xcalloc (1,sizeof *pkt);
4201 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4202 pkt->pkt.secret_key = sk;
4203 add_kbnode(sec_root, new_kbnode( pkt ));
4205 return 0;
4206 #else
4207 return -1;
4208 #endif /*!ENABLE_CARD_SUPPORT*/
4212 #ifdef ENABLE_CARD_SUPPORT
4214 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
4216 int rc;
4217 unsigned char *rsa_n = NULL;
4218 unsigned char *rsa_e = NULL;
4219 unsigned char *rsa_p = NULL;
4220 unsigned char *rsa_q = NULL;
4221 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4222 unsigned char *sexp = NULL;
4223 unsigned char *p;
4224 char numbuf[55], numbuf2[50];
4226 assert (is_RSA (sk->pubkey_algo));
4227 assert (!sk->is_protected);
4229 /* Copy the parameters into straight buffers. */
4230 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4231 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4232 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4233 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4234 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4236 rc = G10ERR_INV_ARG;
4237 goto leave;
4240 /* Put the key into an S-expression. */
4241 sexp = p = xmalloc_secure (30
4242 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4243 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4245 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4246 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4247 p = stpcpy (p, numbuf);
4248 memcpy (p, rsa_n, rsa_n_len);
4249 p += rsa_n_len;
4251 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4252 p = stpcpy (p, numbuf);
4253 memcpy (p, rsa_e, rsa_e_len);
4254 p += rsa_e_len;
4256 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4257 p = stpcpy (p, numbuf);
4258 memcpy (p, rsa_p, rsa_p_len);
4259 p += rsa_p_len;
4261 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4262 p = stpcpy (p, numbuf);
4263 memcpy (p, rsa_q, rsa_q_len);
4264 p += rsa_q_len;
4266 p = stpcpy (p,"))(10:created-at");
4267 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4268 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4269 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4271 /* Fixme: Unfortunately we don't have the serialnumber available -
4272 thus we can't pass it down to the agent. */
4273 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4275 leave:
4276 xfree (sexp);
4277 xfree (rsa_n);
4278 xfree (rsa_e);
4279 xfree (rsa_p);
4280 xfree (rsa_q);
4281 return rc;
4283 #endif /*ENABLE_CARD_SUPPORT*/