typo fixes.
[gnupg.git] / g10 / keygen.c
blob675acf6037d9dfdbc9ebbf940db902e42ca9d146
1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
32 #include "gpg.h"
33 #include "util.h"
34 #include "main.h"
35 #include "packet.h"
36 #include "cipher.h"
37 #include "ttyio.h"
38 #include "options.h"
39 #include "keydb.h"
40 #include "trustdb.h"
41 #include "status.h"
42 #include "i18n.h"
43 #include "keyserver-internal.h"
44 #include "call-agent.h"
47 #define MAX_PREFS 30
49 enum para_name {
50 pKEYTYPE,
51 pKEYLENGTH,
52 pKEYUSAGE,
53 pSUBKEYTYPE,
54 pSUBKEYLENGTH,
55 pSUBKEYUSAGE,
56 pAUTHKEYTYPE,
57 pNAMEREAL,
58 pNAMEEMAIL,
59 pNAMECOMMENT,
60 pPREFERENCES,
61 pREVOKER,
62 pUSERID,
63 pCREATIONDATE,
64 pKEYCREATIONDATE, /* Same in seconds since epoch. */
65 pEXPIREDATE,
66 pKEYEXPIRE, /* in n seconds */
67 pSUBKEYEXPIRE, /* in n seconds */
68 pPASSPHRASE,
69 pPASSPHRASE_DEK,
70 pPASSPHRASE_S2K,
71 pSERIALNO,
72 pBACKUPENCDIR,
73 pHANDLE,
74 pKEYSERVER
77 struct para_data_s {
78 struct para_data_s *next;
79 int lnr;
80 enum para_name key;
81 union {
82 DEK *dek;
83 STRING2KEY *s2k;
84 u32 expire;
85 u32 creation;
86 unsigned int usage;
87 struct revocation_key revkey;
88 char value[1];
89 } u;
92 struct output_control_s {
93 int lnr;
94 int dryrun;
95 int ask_passphrase;
96 int use_files;
97 struct {
98 char *fname;
99 char *newfname;
100 IOBUF stream;
101 armor_filter_context_t *afx;
102 } pub;
103 struct {
104 char *fname;
105 char *newfname;
106 IOBUF stream;
107 armor_filter_context_t *afx;
108 } sec;
112 struct opaque_data_usage_and_pk {
113 unsigned int usage;
114 PKT_public_key *pk;
118 static int prefs_initialized = 0;
119 static byte sym_prefs[MAX_PREFS];
120 static int nsym_prefs;
121 static byte hash_prefs[MAX_PREFS];
122 static int nhash_prefs;
123 static byte zip_prefs[MAX_PREFS];
124 static int nzip_prefs;
125 static int mdc_available,ks_modify;
127 static void do_generate_keypair( struct para_data_s *para,
128 struct output_control_s *outctrl, int card );
129 static int write_keyblock( IOBUF out, KBNODE node );
130 static int gen_card_key (int algo, int keyno, int is_primary,
131 KBNODE pub_root, KBNODE sec_root,
132 PKT_secret_key **ret_sk,
133 u32 *timestamp,
134 u32 expireval, struct para_data_s *para);
135 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
136 KBNODE pub_root, KBNODE sec_root,
137 u32 timestamp,
138 u32 expireval, struct para_data_s *para,
139 const char *backup_dir);
142 static void
143 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
145 byte array[MAX_FINGERPRINT_LEN], *s;
146 char *buf, *p;
147 size_t i, n;
149 if (!handle)
150 handle = "";
152 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
154 p = buf;
155 if (letter || pk)
157 *p++ = letter;
158 *p++ = ' ';
159 fingerprint_from_pk (pk, array, &n);
160 s = array;
161 for (i=0; i < n ; i++, s++, p += 2)
162 sprintf (p, "%02X", *s);
164 if (*handle)
166 *p++ = ' ';
167 for (i=0; handle[i] && i < 100; i++)
168 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
170 *p = 0;
171 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
172 buf);
173 xfree (buf);
176 static void
177 print_status_key_not_created (const char *handle)
179 print_status_key_created (0, NULL, handle);
184 static void
185 write_uid( KBNODE root, const char *s )
187 PACKET *pkt = xmalloc_clear(sizeof *pkt );
188 size_t n = strlen(s);
190 pkt->pkttype = PKT_USER_ID;
191 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
192 pkt->pkt.user_id->len = n;
193 pkt->pkt.user_id->ref = 1;
194 strcpy(pkt->pkt.user_id->name, s);
195 add_kbnode( root, new_kbnode( pkt ) );
198 static void
199 do_add_key_flags (PKT_signature *sig, unsigned int use)
201 byte buf[1];
203 buf[0] = 0;
205 /* The spec says that all primary keys MUST be able to certify. */
206 if(sig->sig_class!=0x18)
207 buf[0] |= 0x01;
209 if (use & PUBKEY_USAGE_SIG)
210 buf[0] |= 0x02;
211 if (use & PUBKEY_USAGE_ENC)
212 buf[0] |= 0x04 | 0x08;
213 if (use & PUBKEY_USAGE_AUTH)
214 buf[0] |= 0x20;
216 if (!buf[0])
217 return;
219 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
224 keygen_add_key_expire( PKT_signature *sig, void *opaque )
226 PKT_public_key *pk = opaque;
227 byte buf[8];
228 u32 u;
230 if( pk->expiredate ) {
231 if(pk->expiredate > pk->timestamp)
232 u= pk->expiredate - pk->timestamp;
233 else
234 u= 1;
236 buf[0] = (u >> 24) & 0xff;
237 buf[1] = (u >> 16) & 0xff;
238 buf[2] = (u >> 8) & 0xff;
239 buf[3] = u & 0xff;
240 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
242 else
244 /* Make sure we don't leave a key expiration subpacket lying
245 around */
246 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
249 return 0;
252 static int
253 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
255 struct opaque_data_usage_and_pk *oduap = opaque;
257 do_add_key_flags (sig, oduap->usage);
258 return keygen_add_key_expire (sig, oduap->pk);
261 static int
262 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
264 int i;
266 for (i=0; i < *nbuf; i++ )
267 if (buf[i] == val)
269 log_info (_("preference `%s' duplicated\n"), item);
270 return -1;
273 if (*nbuf >= MAX_PREFS)
275 if(type==1)
276 log_info(_("too many cipher preferences\n"));
277 else if(type==2)
278 log_info(_("too many digest preferences\n"));
279 else if(type==3)
280 log_info(_("too many compression preferences\n"));
281 else
282 BUG();
284 return -1;
287 buf[(*nbuf)++] = val;
288 return 0;
292 * Parse the supplied string and use it to set the standard
293 * preferences. The string may be in a form like the one printed by
294 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
295 * cipher/hash/compress names. Use NULL to set the default
296 * preferences. Returns: 0 = okay
299 keygen_set_std_prefs (const char *string,int personal)
301 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
302 int nsym=0, nhash=0, nzip=0, val, rc=0;
303 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
304 char dummy_string[45+1]; /* Enough for 15 items. */
306 if (!string || !ascii_strcasecmp (string, "default"))
308 if (opt.def_preference_list)
309 string=opt.def_preference_list;
310 else
312 dummy_string[0]='\0';
314 /* The rationale why we use the order AES256,192,128 is
315 for compatibility reasons with PGP. If gpg would
316 define AES128 first, we would get the somewhat
317 confusing situation:
319 gpg -r pgpkey -r gpgkey ---gives--> AES256
320 gpg -r gpgkey -r pgpkey ---gives--> AES
322 Note that by using --personal-cipher-preferences it is
323 possible to prefer AES128.
326 /* Make sure we do not add more than 15 items here, as we
327 could overflow the size of dummy_string. We currently
328 have at most 12. */
329 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
330 strcat(dummy_string,"S9 ");
331 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
332 strcat(dummy_string,"S8 ");
333 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
334 strcat(dummy_string,"S7 ");
335 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
336 strcat(dummy_string,"S3 ");
337 strcat(dummy_string,"S2 "); /* 3DES */
338 /* If we have it, IDEA goes *after* 3DES so it won't be
339 used unless we're encrypting along with a V3 key.
340 Ideally, we would only put the S1 preference in if the
341 key was RSA and <=2048 bits, as that is what won't
342 break PGP2, but that is difficult with the current
343 code, and not really worth checking as a non-RSA <=2048
344 bit key wouldn't be usable by PGP2 anyway. -dms */
345 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
346 strcat(dummy_string,"S1 ");
348 /* SHA-1 */
349 strcat(dummy_string,"H2 ");
351 if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256))
352 strcat(dummy_string,"H8 ");
354 /* RIPEMD160 */
355 strcat(dummy_string,"H3 ");
357 /* ZLIB */
358 strcat(dummy_string,"Z2 ");
360 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
361 strcat(dummy_string,"Z3 ");
363 /* ZIP */
364 strcat(dummy_string,"Z1");
366 string=dummy_string;
369 else if (!ascii_strcasecmp (string, "none"))
370 string = "";
372 if(strlen(string))
374 char *tok,*prefstring;
376 prefstring=xstrdup(string); /* need a writable string! */
378 while((tok=strsep(&prefstring," ,")))
380 if((val=string_to_cipher_algo (tok)))
382 if(set_one_pref(val,1,tok,sym,&nsym))
383 rc=-1;
385 else if((val=string_to_digest_algo (tok)))
387 if(set_one_pref(val,2,tok,hash,&nhash))
388 rc=-1;
390 else if((val=string_to_compress_algo(tok))>-1)
392 if(set_one_pref(val,3,tok,zip,&nzip))
393 rc=-1;
395 else if (ascii_strcasecmp(tok,"mdc")==0)
396 mdc=1;
397 else if (ascii_strcasecmp(tok,"no-mdc")==0)
398 mdc=0;
399 else if (ascii_strcasecmp(tok,"ks-modify")==0)
400 modify=1;
401 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
402 modify=0;
403 else
405 log_info (_("invalid item `%s' in preference string\n"),tok);
407 /* Complain if IDEA is not available. */
408 if(ascii_strcasecmp(tok,"s1")==0
409 || ascii_strcasecmp(tok,"idea")==0)
410 idea_cipher_warn(1);
412 rc=-1;
416 xfree(prefstring);
419 if(!rc)
421 if(personal)
423 if(personal==PREFTYPE_SYM)
425 xfree(opt.personal_cipher_prefs);
427 if(nsym==0)
428 opt.personal_cipher_prefs=NULL;
429 else
431 int i;
433 opt.personal_cipher_prefs=
434 xmalloc(sizeof(prefitem_t *)*(nsym+1));
436 for (i=0; i<nsym; i++)
438 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
439 opt.personal_cipher_prefs[i].value = sym[i];
442 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
443 opt.personal_cipher_prefs[i].value = 0;
446 else if(personal==PREFTYPE_HASH)
448 xfree(opt.personal_digest_prefs);
450 if(nhash==0)
451 opt.personal_digest_prefs=NULL;
452 else
454 int i;
456 opt.personal_digest_prefs=
457 xmalloc(sizeof(prefitem_t *)*(nhash+1));
459 for (i=0; i<nhash; i++)
461 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
462 opt.personal_digest_prefs[i].value = hash[i];
465 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
466 opt.personal_digest_prefs[i].value = 0;
469 else if(personal==PREFTYPE_ZIP)
471 xfree(opt.personal_compress_prefs);
473 if(nzip==0)
474 opt.personal_compress_prefs=NULL;
475 else
477 int i;
479 opt.personal_compress_prefs=
480 xmalloc(sizeof(prefitem_t *)*(nzip+1));
482 for (i=0; i<nzip; i++)
484 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
485 opt.personal_compress_prefs[i].value = zip[i];
488 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
489 opt.personal_compress_prefs[i].value = 0;
493 else
495 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
496 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
497 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
498 mdc_available = mdc;
499 ks_modify = modify;
500 prefs_initialized = 1;
504 return rc;
507 /* Return a fake user ID containing the preferences. Caller must
508 free. */
509 PKT_user_id *keygen_get_std_prefs(void)
511 int i,j=0;
512 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
514 if(!prefs_initialized)
515 keygen_set_std_prefs(NULL,0);
517 uid->ref=1;
519 uid->prefs=xmalloc((sizeof(prefitem_t *)*
520 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
522 for(i=0;i<nsym_prefs;i++,j++)
524 uid->prefs[j].type=PREFTYPE_SYM;
525 uid->prefs[j].value=sym_prefs[i];
528 for(i=0;i<nhash_prefs;i++,j++)
530 uid->prefs[j].type=PREFTYPE_HASH;
531 uid->prefs[j].value=hash_prefs[i];
534 for(i=0;i<nzip_prefs;i++,j++)
536 uid->prefs[j].type=PREFTYPE_ZIP;
537 uid->prefs[j].value=zip_prefs[i];
540 uid->prefs[j].type=PREFTYPE_NONE;
541 uid->prefs[j].value=0;
543 uid->flags.mdc=mdc_available;
544 uid->flags.ks_modify=ks_modify;
546 return uid;
549 static void
550 add_feature_mdc (PKT_signature *sig,int enabled)
552 const byte *s;
553 size_t n;
554 int i;
555 char *buf;
557 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
558 /* Already set or cleared */
559 if (s && n &&
560 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
561 return;
563 if (!s || !n) { /* create a new one */
564 n = 1;
565 buf = xmalloc_clear (n);
567 else {
568 buf = xmalloc (n);
569 memcpy (buf, s, n);
572 if(enabled)
573 buf[0] |= 0x01; /* MDC feature */
574 else
575 buf[0] &= ~0x01;
577 /* Are there any bits set? */
578 for(i=0;i<n;i++)
579 if(buf[i]!=0)
580 break;
582 if(i==n)
583 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
584 else
585 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
587 xfree (buf);
590 static void
591 add_keyserver_modify (PKT_signature *sig,int enabled)
593 const byte *s;
594 size_t n;
595 int i;
596 char *buf;
598 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
599 enabled=!enabled;
601 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
602 /* Already set or cleared */
603 if (s && n &&
604 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
605 return;
607 if (!s || !n) { /* create a new one */
608 n = 1;
609 buf = xmalloc_clear (n);
611 else {
612 buf = xmalloc (n);
613 memcpy (buf, s, n);
616 if(enabled)
617 buf[0] |= 0x80; /* no-modify flag */
618 else
619 buf[0] &= ~0x80;
621 /* Are there any bits set? */
622 for(i=0;i<n;i++)
623 if(buf[i]!=0)
624 break;
626 if(i==n)
627 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
628 else
629 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
631 xfree (buf);
636 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
638 (void)opaque;
640 if (!prefs_initialized)
641 keygen_set_std_prefs (NULL, 0);
643 if (nsym_prefs)
644 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
645 else
647 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
648 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
651 if (nhash_prefs)
652 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
653 else
655 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
656 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
659 if (nzip_prefs)
660 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
661 else
663 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
664 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
667 /* Make sure that the MDC feature flag is set if needed. */
668 add_feature_mdc (sig,mdc_available);
669 add_keyserver_modify (sig,ks_modify);
670 keygen_add_keyserver_url(sig,NULL);
672 return 0;
676 /****************
677 * Add preference to the self signature packet.
678 * This is only called for packets with version > 3.
682 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
684 PKT_public_key *pk = opaque;
686 do_add_key_flags (sig, pk->pubkey_usage);
687 keygen_add_key_expire( sig, opaque );
688 keygen_upd_std_prefs (sig, opaque);
689 keygen_add_keyserver_url(sig,NULL);
691 return 0;
695 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
697 const char *url=opaque;
699 if(!url)
700 url=opt.def_keyserver_url;
702 if(url)
703 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
704 else
705 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
707 return 0;
711 keygen_add_notations(PKT_signature *sig,void *opaque)
713 struct notation *notation;
715 /* We always start clean */
716 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
717 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
718 sig->flags.notation=0;
720 for(notation=opaque;notation;notation=notation->next)
721 if(!notation->flags.ignore)
723 unsigned char *buf;
724 unsigned int n1,n2;
726 n1=strlen(notation->name);
727 if(notation->altvalue)
728 n2=strlen(notation->altvalue);
729 else if(notation->bdat)
730 n2=notation->blen;
731 else
732 n2=strlen(notation->value);
734 buf = xmalloc( 8 + n1 + n2 );
736 /* human readable or not */
737 buf[0] = notation->bdat?0:0x80;
738 buf[1] = buf[2] = buf[3] = 0;
739 buf[4] = n1 >> 8;
740 buf[5] = n1;
741 buf[6] = n2 >> 8;
742 buf[7] = n2;
743 memcpy(buf+8, notation->name, n1 );
744 if(notation->altvalue)
745 memcpy(buf+8+n1, notation->altvalue, n2 );
746 else if(notation->bdat)
747 memcpy(buf+8+n1, notation->bdat, n2 );
748 else
749 memcpy(buf+8+n1, notation->value, n2 );
750 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
751 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
752 buf, 8+n1+n2 );
753 xfree(buf);
756 return 0;
760 keygen_add_revkey(PKT_signature *sig, void *opaque)
762 struct revocation_key *revkey=opaque;
763 byte buf[2+MAX_FINGERPRINT_LEN];
765 buf[0]=revkey->class;
766 buf[1]=revkey->algid;
767 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
769 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
771 /* All sigs with revocation keys set are nonrevocable */
772 sig->flags.revocable=0;
773 buf[0] = 0;
774 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
776 parse_revkeys(sig);
778 return 0;
783 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
784 signature creation time. */
786 make_backsig (PKT_signature *sig,PKT_public_key *pk,
787 PKT_public_key *sub_pk,PKT_secret_key *sub_sk,
788 u32 timestamp)
790 PKT_signature *backsig;
791 int rc;
793 cache_public_key(sub_pk);
795 rc = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_sk, 0x19,
796 0, 0, timestamp, 0, NULL, NULL);
797 if(rc)
798 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
799 else
801 /* Get it into a binary packed form. */
802 IOBUF backsig_out=iobuf_temp();
803 PACKET backsig_pkt;
805 init_packet(&backsig_pkt);
806 backsig_pkt.pkttype=PKT_SIGNATURE;
807 backsig_pkt.pkt.signature=backsig;
808 rc=build_packet(backsig_out,&backsig_pkt);
809 free_packet(&backsig_pkt);
810 if(rc)
811 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
812 else
814 size_t pktlen=0;
815 byte *buf=iobuf_get_temp_buffer(backsig_out);
817 /* Remove the packet header */
818 if(buf[0]&0x40)
820 if(buf[1]<192)
822 pktlen=buf[1];
823 buf+=2;
825 else if(buf[1]<224)
827 pktlen=(buf[1]-192)*256;
828 pktlen+=buf[2]+192;
829 buf+=3;
831 else if(buf[1]==255)
833 pktlen =buf[2] << 24;
834 pktlen|=buf[3] << 16;
835 pktlen|=buf[4] << 8;
836 pktlen|=buf[5];
837 buf+=6;
839 else
840 BUG();
842 else
844 int mark=1;
846 switch(buf[0]&3)
848 case 3:
849 BUG();
850 break;
852 case 2:
853 pktlen =buf[mark++] << 24;
854 pktlen|=buf[mark++] << 16;
856 case 1:
857 pktlen|=buf[mark++] << 8;
859 case 0:
860 pktlen|=buf[mark++];
863 buf+=mark;
866 /* Now make the binary blob into a subpacket. */
867 build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
869 iobuf_close(backsig_out);
873 return rc;
877 static int
878 write_direct_sig (KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
879 struct revocation_key *revkey, u32 timestamp)
881 PACKET *pkt;
882 PKT_signature *sig;
883 int rc=0;
884 KBNODE node;
885 PKT_public_key *pk;
887 if( opt.verbose )
888 log_info(_("writing direct signature\n"));
890 /* Get the pk packet from the pub_tree. */
891 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
892 if( !node )
893 BUG();
894 pk = node->pkt->pkt.public_key;
896 /* We have to cache the key, so that the verification of the
897 signature creation is able to retrieve the public key. */
898 cache_public_key (pk);
900 /* Make the signature. */
901 rc = make_keysig_packet (&sig,pk,NULL,NULL,sk,0x1F,
902 0, 0, timestamp, 0,
903 keygen_add_revkey, revkey);
904 if( rc )
906 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
907 return rc;
910 pkt = xmalloc_clear( sizeof *pkt );
911 pkt->pkttype = PKT_SIGNATURE;
912 pkt->pkt.signature = sig;
913 add_kbnode( root, new_kbnode( pkt ) );
914 return rc;
918 static int
919 write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
920 unsigned int use, u32 timestamp )
922 PACKET *pkt;
923 PKT_signature *sig;
924 PKT_user_id *uid;
925 int rc=0;
926 KBNODE node;
927 PKT_public_key *pk;
929 if( opt.verbose )
930 log_info(_("writing self signature\n"));
932 /* Get the uid packet from the list. */
933 node = find_kbnode( pub_root, PKT_USER_ID );
934 if( !node )
935 BUG(); /* No user id packet in tree. */
936 uid = node->pkt->pkt.user_id;
938 /* Get the pk packet from the pub_tree. */
939 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
940 if( !node )
941 BUG();
942 pk = node->pkt->pkt.public_key;
943 pk->pubkey_usage = use;
945 /* We have to cache the key, so that the verification of the
946 signature creation is able to retrieve the public key. */
947 cache_public_key (pk);
949 /* Make the signature. */
950 rc = make_keysig_packet (&sig, pk, uid, NULL, sk, 0x13,
951 0, 0, timestamp, 0,
952 keygen_add_std_prefs, pk);
953 if( rc )
955 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
956 return rc;
959 pkt = xmalloc_clear( sizeof *pkt );
960 pkt->pkttype = PKT_SIGNATURE;
961 pkt->pkt.signature = sig;
962 add_kbnode( sec_root, new_kbnode( pkt ) );
964 pkt = xmalloc_clear( sizeof *pkt );
965 pkt->pkttype = PKT_SIGNATURE;
966 pkt->pkt.signature = copy_signature(NULL,sig);
967 add_kbnode( pub_root, new_kbnode( pkt ) );
968 return rc;
972 /* Write the key binding signature. If TIMESTAMP is not NULL use the
973 signature creation times. */
974 static int
975 write_keybinding (KBNODE root, KBNODE pub_root,
976 PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
977 unsigned int use, u32 timestamp)
979 PACKET *pkt;
980 PKT_signature *sig;
981 int rc=0;
982 KBNODE node;
983 PKT_public_key *pri_pk, *sub_pk;
984 struct opaque_data_usage_and_pk oduap;
986 if ( opt.verbose )
987 log_info(_("writing key binding signature\n"));
989 /* Get the pk packet from the pub_tree. */
990 node = find_kbnode ( pub_root, PKT_PUBLIC_KEY );
991 if ( !node )
992 BUG();
993 pri_pk = node->pkt->pkt.public_key;
995 /* We have to cache the key, so that the verification of the
996 * signature creation is able to retrieve the public key. */
997 cache_public_key (pri_pk);
999 /* Find the last subkey. */
1000 sub_pk = NULL;
1001 for (node=pub_root; node; node = node->next )
1003 if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
1004 sub_pk = node->pkt->pkt.public_key;
1006 if (!sub_pk)
1007 BUG();
1009 /* Make the signature. */
1010 oduap.usage = use;
1011 oduap.pk = sub_pk;
1012 rc = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18,
1013 0, 0, timestamp, 0,
1014 keygen_add_key_flags_and_expire, &oduap );
1015 if (rc)
1017 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc) );
1018 return rc;
1021 /* Make a backsig. */
1022 if (use&PUBKEY_USAGE_SIG)
1024 rc = make_backsig (sig, pri_pk, sub_pk, sub_sk, timestamp);
1025 if (rc)
1026 return rc;
1029 pkt = xmalloc_clear ( sizeof *pkt );
1030 pkt->pkttype = PKT_SIGNATURE;
1031 pkt->pkt.signature = sig;
1032 add_kbnode (root, new_kbnode (pkt) );
1033 return rc;
1038 static int
1039 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1040 const char *topname, const char *elems)
1042 gcry_sexp_t list, l2;
1043 const char *s;
1044 int i, idx;
1045 int rc = 0;
1047 list = gcry_sexp_find_token (sexp, topname, 0);
1048 if (!list)
1049 return gpg_error (GPG_ERR_INV_OBJ);
1050 l2 = gcry_sexp_cadr (list);
1051 gcry_sexp_release (list);
1052 list = l2;
1053 if (!list)
1054 return gpg_error (GPG_ERR_NO_OBJ);
1056 for (idx=0,s=elems; *s; s++, idx++)
1058 l2 = gcry_sexp_find_token (list, s, 1);
1059 if (!l2)
1061 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1062 goto leave;
1064 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1065 gcry_sexp_release (l2);
1066 if (!array[idx])
1068 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1069 goto leave;
1072 gcry_sexp_release (list);
1074 leave:
1075 if (rc)
1077 for (i=0; i<idx; i++)
1079 xfree (array[i]);
1080 array[i] = NULL;
1082 gcry_sexp_release (list);
1084 return rc;
1088 static int
1089 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
1091 int rc = 0;
1093 if (dek)
1095 sk->protect.algo = dek->algo;
1096 sk->protect.s2k = *s2k;
1097 rc = protect_secret_key (sk, dek);
1098 if (rc)
1099 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
1102 return rc;
1105 static void
1106 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
1108 (void)misc_key_info;
1109 (void)sec_root;
1110 #if 0 /* Not used anymore */
1111 size_t n;
1112 char *buf;
1114 if (misc_key_info)
1116 /* DSA: don't know whether it makes sense to have the factors, so for now
1117 we store them in the secret keyring (but they are not secret)
1118 p = 2 * q * f1 * f2 * ... * fn
1119 We store only f1 to f_n-1; fn can be calculated because p and q
1120 are known. */
1121 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
1122 buf = xmalloc (n+4);
1123 strcpy (buf, "#::");
1124 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
1125 if (n)
1127 n += 3;
1128 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
1130 xfree (buf);
1131 gcry_sexp_release (misc_key_info);
1133 #endif
1137 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1138 time to be put into the key structure. */
1139 static int
1140 gen_elg (int algo, unsigned int nbits,
1141 KBNODE pub_root, KBNODE sec_root, DEK *dek,
1142 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1143 u32 timestamp, u32 expireval, int is_subkey)
1145 int rc;
1146 PACKET *pkt;
1147 PKT_secret_key *sk;
1148 PKT_public_key *pk;
1149 gcry_sexp_t s_parms, s_key;
1150 gcry_sexp_t misc_key_info;
1152 assert( is_ELGAMAL(algo) );
1154 if (nbits < 512)
1156 nbits = 1024;
1157 log_info (_("keysize invalid; using %u bits\n"), nbits );
1160 if ((nbits % 32))
1162 nbits = ((nbits + 31) / 32) * 32;
1163 log_info (_("keysize rounded up to %u bits\n"), nbits );
1167 rc = gcry_sexp_build ( &s_parms, NULL,
1168 "(genkey(%s(nbits %d)))",
1169 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1170 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1171 (int)nbits);
1172 if (rc)
1173 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1175 rc = gcry_pk_genkey (&s_key, s_parms);
1176 gcry_sexp_release (s_parms);
1177 if (rc)
1179 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1180 return rc;
1183 sk = xmalloc_clear( sizeof *sk );
1184 pk = xmalloc_clear( sizeof *pk );
1185 sk->timestamp = pk->timestamp = timestamp;
1186 sk->version = pk->version = 4;
1187 if (expireval)
1189 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1191 sk->pubkey_algo = pk->pubkey_algo = algo;
1193 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
1194 if (rc)
1196 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1197 gcry_sexp_release (s_key);
1198 free_secret_key (sk);
1199 free_public_key (pk);
1200 return rc;
1202 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
1203 if (rc)
1205 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1206 gcry_sexp_release (s_key);
1207 free_secret_key (sk);
1208 free_public_key (pk);
1209 return rc;
1211 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1212 gcry_sexp_release (s_key);
1214 sk->is_protected = 0;
1215 sk->protect.algo = 0;
1217 sk->csum = checksum_mpi (sk->skey[3]);
1218 if (ret_sk) /* Return an unprotected version of the sk. */
1219 *ret_sk = copy_secret_key ( NULL, sk );
1221 rc = genhelp_protect (dek, s2k, sk);
1222 if (rc)
1224 free_public_key (pk);
1225 free_secret_key (sk);
1226 gcry_sexp_release (misc_key_info);
1227 return rc;
1230 pkt = xmalloc_clear (sizeof *pkt);
1231 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1232 pkt->pkt.public_key = pk;
1233 add_kbnode (pub_root, new_kbnode( pkt ));
1235 /* Don't know whether it makes sense to have access to the factors,
1236 so for now we store them in the secret keyring (but they are not
1237 secret). */
1238 pkt = xmalloc_clear (sizeof *pkt);
1239 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1240 pkt->pkt.secret_key = sk;
1241 add_kbnode (sec_root, new_kbnode( pkt ));
1243 genhelp_factors (misc_key_info, sec_root);
1245 return 0;
1249 /****************
1250 * Generate a DSA key
1252 static int
1253 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1254 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1255 u32 timestamp, u32 expireval, int is_subkey)
1257 int rc;
1258 PACKET *pkt;
1259 PKT_secret_key *sk;
1260 PKT_public_key *pk;
1261 gcry_sexp_t s_parms, s_key;
1262 gcry_sexp_t misc_key_info;
1263 unsigned int qbits;
1265 if ( nbits < 512 || (!opt.flags.dsa2 && nbits > 1024))
1267 nbits = 1024;
1268 log_info(_("keysize invalid; using %u bits\n"), nbits );
1270 else if ( nbits > 3072 )
1272 nbits = 3072;
1273 log_info(_("keysize invalid; using %u bits\n"), nbits );
1276 if( (nbits % 64) )
1278 nbits = ((nbits + 63) / 64) * 64;
1279 log_info(_("keysize rounded up to %u bits\n"), nbits );
1283 Figure out a q size based on the key size. FIPS 180-3 says:
1285 L = 1024, N = 160
1286 L = 2048, N = 224
1287 L = 2048, N = 256
1288 L = 3072, N = 256
1290 2048/256 is an odd pair since there is also a 2048/224 and
1291 3072/256. Matching sizes is not a very exact science.
1293 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1294 but less than 2048, and 160 for 1024 (DSA1).
1297 if (nbits > 2048)
1298 qbits = 256;
1299 else if ( nbits > 1024)
1300 qbits = 224;
1301 else
1302 qbits = 160;
1304 if (qbits != 160 )
1305 log_info (_("WARNING: some OpenPGP programs can't"
1306 " handle a DSA key with this digest size\n"));
1308 rc = gcry_sexp_build (&s_parms, NULL,
1309 "(genkey(dsa(nbits %d)(qbits %d)))",
1310 (int)nbits, (int)qbits);
1311 if (rc)
1312 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1314 rc = gcry_pk_genkey (&s_key, s_parms);
1315 gcry_sexp_release (s_parms);
1316 if (rc)
1318 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1319 return rc;
1322 sk = xmalloc_clear( sizeof *sk );
1323 pk = xmalloc_clear( sizeof *pk );
1324 sk->timestamp = pk->timestamp = timestamp;
1325 sk->version = pk->version = 4;
1326 if (expireval)
1327 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1328 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1330 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1331 if (rc)
1333 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1334 gcry_sexp_release (s_key);
1335 free_public_key(pk);
1336 free_secret_key(sk);
1337 return rc;
1339 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1340 if (rc)
1342 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1343 gcry_sexp_release (s_key);
1344 free_public_key(pk);
1345 free_secret_key(sk);
1346 return rc;
1348 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1349 gcry_sexp_release (s_key);
1351 sk->is_protected = 0;
1352 sk->protect.algo = 0;
1354 sk->csum = checksum_mpi ( sk->skey[4] );
1355 if( ret_sk ) /* return an unprotected version of the sk */
1356 *ret_sk = copy_secret_key( NULL, sk );
1358 rc = genhelp_protect (dek, s2k, sk);
1359 if (rc)
1361 free_public_key (pk);
1362 free_secret_key (sk);
1363 gcry_sexp_release (misc_key_info);
1364 return rc;
1367 pkt = xmalloc_clear(sizeof *pkt);
1368 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1369 pkt->pkt.public_key = pk;
1370 add_kbnode(pub_root, new_kbnode( pkt ));
1372 /* Don't know whether it makes sense to have the factors, so for now
1373 * we store them in the secret keyring (but they are not secret)
1374 * p = 2 * q * f1 * f2 * ... * fn
1375 * We store only f1 to f_n-1; fn can be calculated because p and q
1376 * are known.
1378 pkt = xmalloc_clear(sizeof *pkt);
1379 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1380 pkt->pkt.secret_key = sk;
1381 add_kbnode(sec_root, new_kbnode( pkt ));
1383 genhelp_factors (misc_key_info, sec_root);
1385 return 0;
1390 * Generate an RSA key.
1392 static int
1393 gen_rsa (int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1394 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1395 u32 timestamp, u32 expireval, int is_subkey)
1397 int rc;
1398 PACKET *pkt;
1399 PKT_secret_key *sk;
1400 PKT_public_key *pk;
1401 gcry_sexp_t s_parms, s_key;
1403 assert (is_RSA(algo));
1405 if (nbits < 1024)
1407 nbits = 1024;
1408 log_info (_("keysize invalid; using %u bits\n"), nbits );
1411 if ((nbits % 32))
1413 nbits = ((nbits + 31) / 32) * 32;
1414 log_info (_("keysize rounded up to %u bits\n"), nbits );
1417 rc = gcry_sexp_build (&s_parms, NULL,
1418 "(genkey(rsa(nbits %d)))",
1419 (int)nbits);
1420 if (rc)
1421 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1423 rc = gcry_pk_genkey (&s_key, s_parms);
1424 gcry_sexp_release (s_parms);
1425 if (rc)
1427 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1428 return rc;
1431 sk = xmalloc_clear( sizeof *sk );
1432 pk = xmalloc_clear( sizeof *pk );
1433 sk->timestamp = pk->timestamp = timestamp;
1434 sk->version = pk->version = 4;
1435 if (expireval)
1437 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1439 sk->pubkey_algo = pk->pubkey_algo = algo;
1441 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1442 if (rc)
1444 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1445 gcry_sexp_release (s_key);
1446 free_public_key(pk);
1447 free_secret_key(sk);
1448 return rc;
1450 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1451 if (rc)
1453 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1454 gcry_sexp_release (s_key);
1455 free_public_key(pk);
1456 free_secret_key(sk);
1457 return rc;
1459 gcry_sexp_release (s_key);
1461 sk->is_protected = 0;
1462 sk->protect.algo = 0;
1464 sk->csum = checksum_mpi (sk->skey[2] );
1465 sk->csum += checksum_mpi (sk->skey[3] );
1466 sk->csum += checksum_mpi (sk->skey[4] );
1467 sk->csum += checksum_mpi (sk->skey[5] );
1468 if( ret_sk ) /* return an unprotected version of the sk */
1469 *ret_sk = copy_secret_key( NULL, sk );
1471 rc = genhelp_protect (dek, s2k, sk);
1472 if (rc)
1474 free_public_key (pk);
1475 free_secret_key (sk);
1476 return rc;
1479 pkt = xmalloc_clear(sizeof *pkt);
1480 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1481 pkt->pkt.public_key = pk;
1482 add_kbnode(pub_root, new_kbnode( pkt ));
1484 pkt = xmalloc_clear(sizeof *pkt);
1485 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1486 pkt->pkt.secret_key = sk;
1487 add_kbnode(sec_root, new_kbnode( pkt ));
1489 return 0;
1493 /****************
1494 * check valid days:
1495 * return 0 on error or the multiplier
1497 static int
1498 check_valid_days( const char *s )
1500 if( !digitp(s) )
1501 return 0;
1502 for( s++; *s; s++)
1503 if( !digitp(s) )
1504 break;
1505 if( !*s )
1506 return 1;
1507 if( s[1] )
1508 return 0; /* e.g. "2323wc" */
1509 if( *s == 'd' || *s == 'D' )
1510 return 1;
1511 if( *s == 'w' || *s == 'W' )
1512 return 7;
1513 if( *s == 'm' || *s == 'M' )
1514 return 30;
1515 if( *s == 'y' || *s == 'Y' )
1516 return 365;
1517 return 0;
1521 static void
1522 print_key_flags(int flags)
1524 if(flags&PUBKEY_USAGE_SIG)
1525 tty_printf("%s ",_("Sign"));
1527 if(flags&PUBKEY_USAGE_CERT)
1528 tty_printf("%s ",_("Certify"));
1530 if(flags&PUBKEY_USAGE_ENC)
1531 tty_printf("%s ",_("Encrypt"));
1533 if(flags&PUBKEY_USAGE_AUTH)
1534 tty_printf("%s ",_("Authenticate"));
1538 /* Returns the key flags */
1539 static unsigned int
1540 ask_key_flags(int algo,int subkey)
1542 /* TRANSLATORS: Please use only plain ASCII characters for the
1543 translation. If this is not possible use single digits. The
1544 string needs to 8 bytes long. Here is a description of the
1545 functions:
1547 s = Toggle signing capability
1548 e = Toggle encryption capability
1549 a = Toggle authentication capability
1550 q = Finish
1552 const char *togglers=_("SsEeAaQq");
1553 char *answer=NULL;
1554 unsigned int current=0;
1555 unsigned int possible=openpgp_pk_algo_usage(algo);
1557 if ( strlen(togglers) != 7 )
1559 tty_printf ("NOTE: Bad translation at %s:%d. "
1560 "Please report.\n", __FILE__, __LINE__);
1561 togglers = "11223300";
1564 /* Only primary keys may certify. */
1565 if(subkey)
1566 possible&=~PUBKEY_USAGE_CERT;
1568 /* Preload the current set with the possible set, minus
1569 authentication, since nobody really uses auth yet. */
1570 current=possible&~PUBKEY_USAGE_AUTH;
1572 for(;;)
1574 tty_printf("\n");
1575 tty_printf(_("Possible actions for a %s key: "),
1576 gcry_pk_algo_name (algo));
1577 print_key_flags(possible);
1578 tty_printf("\n");
1579 tty_printf(_("Current allowed actions: "));
1580 print_key_flags(current);
1581 tty_printf("\n\n");
1583 if(possible&PUBKEY_USAGE_SIG)
1584 tty_printf(_(" (%c) Toggle the sign capability\n"),
1585 togglers[0]);
1586 if(possible&PUBKEY_USAGE_ENC)
1587 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1588 togglers[2]);
1589 if(possible&PUBKEY_USAGE_AUTH)
1590 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1591 togglers[4]);
1593 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1594 tty_printf("\n");
1596 xfree(answer);
1597 answer = cpr_get("keygen.flags",_("Your selection? "));
1598 cpr_kill_prompt();
1600 if(strlen(answer)>1)
1601 tty_printf(_("Invalid selection.\n"));
1602 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1603 break;
1604 else if((*answer==togglers[0] || *answer==togglers[1])
1605 && possible&PUBKEY_USAGE_SIG)
1607 if(current&PUBKEY_USAGE_SIG)
1608 current&=~PUBKEY_USAGE_SIG;
1609 else
1610 current|=PUBKEY_USAGE_SIG;
1612 else if((*answer==togglers[2] || *answer==togglers[3])
1613 && possible&PUBKEY_USAGE_ENC)
1615 if(current&PUBKEY_USAGE_ENC)
1616 current&=~PUBKEY_USAGE_ENC;
1617 else
1618 current|=PUBKEY_USAGE_ENC;
1620 else if((*answer==togglers[4] || *answer==togglers[5])
1621 && possible&PUBKEY_USAGE_AUTH)
1623 if(current&PUBKEY_USAGE_AUTH)
1624 current&=~PUBKEY_USAGE_AUTH;
1625 else
1626 current|=PUBKEY_USAGE_AUTH;
1628 else
1629 tty_printf(_("Invalid selection.\n"));
1632 xfree(answer);
1634 return current;
1638 /****************
1639 * Returns: 0 to create both a DSA and a Elgamal key.
1640 * and only if key flags are to be written the desired usage.
1642 static int
1643 ask_algo (int addmode, unsigned int *r_usage)
1645 char *answer;
1646 int algo;
1648 *r_usage = 0;
1649 tty_printf(_("Please select what kind of key you want:\n"));
1650 if( !addmode )
1651 tty_printf(_(" (%d) DSA and Elgamal (default)\n"), 1 );
1652 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
1653 if (opt.expert)
1654 tty_printf( _(" (%d) DSA (set your own capabilities)\n"), 3 );
1655 if( addmode )
1656 tty_printf(_(" (%d) Elgamal (encrypt only)\n"), 4 );
1657 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
1658 if (addmode)
1659 tty_printf(_(" (%d) RSA (encrypt only)\n"), 6 );
1660 if (opt.expert)
1661 tty_printf( _(" (%d) RSA (set your own capabilities)\n"), 7 );
1663 for(;;) {
1664 answer = cpr_get("keygen.algo",_("Your selection? "));
1665 cpr_kill_prompt();
1666 algo = *answer? atoi(answer): 1;
1667 xfree(answer);
1668 if( algo == 1 && !addmode ) {
1669 algo = 0; /* create both keys */
1670 break;
1672 else if( algo == 7 && opt.expert ) {
1673 algo = PUBKEY_ALGO_RSA;
1674 *r_usage=ask_key_flags(algo,addmode);
1675 break;
1677 else if( algo == 6 && addmode ) {
1678 algo = PUBKEY_ALGO_RSA;
1679 *r_usage = PUBKEY_USAGE_ENC;
1680 break;
1682 else if( algo == 5 ) {
1683 algo = PUBKEY_ALGO_RSA;
1684 *r_usage = PUBKEY_USAGE_SIG;
1685 break;
1687 else if( algo == 4 && addmode ) {
1688 algo = PUBKEY_ALGO_ELGAMAL_E;
1689 *r_usage = PUBKEY_USAGE_ENC;
1690 break;
1692 else if( algo == 3 && opt.expert ) {
1693 algo = PUBKEY_ALGO_DSA;
1694 *r_usage=ask_key_flags(algo,addmode);
1695 break;
1697 else if( algo == 2 ) {
1698 algo = PUBKEY_ALGO_DSA;
1699 *r_usage = PUBKEY_USAGE_SIG;
1700 break;
1702 else
1703 tty_printf(_("Invalid selection.\n"));
1706 return algo;
1710 static unsigned
1711 ask_keysize( int algo )
1713 unsigned int nbits, min, def=2048, max=4096;
1715 if(opt.expert)
1716 min=512;
1717 else
1718 min=1024;
1720 switch(algo)
1722 case PUBKEY_ALGO_DSA:
1723 if(opt.flags.dsa2)
1725 def=1024;
1726 max=3072;
1728 else
1730 tty_printf(_("DSA keypair will have %u bits.\n"),1024);
1731 return 1024;
1733 break;
1735 case PUBKEY_ALGO_RSA:
1736 min=1024;
1737 break;
1740 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1741 gcry_pk_algo_name (algo), min, max);
1743 for(;;)
1745 char *prompt,*answer;
1747 #define PROMPTSTRING _("What keysize do you want? (%u) ")
1749 prompt=xmalloc(strlen(PROMPTSTRING)+20);
1750 sprintf(prompt,PROMPTSTRING,def);
1752 #undef PROMPTSTRING
1754 answer = cpr_get("keygen.size",prompt);
1755 cpr_kill_prompt();
1756 nbits = *answer? atoi(answer): def;
1757 xfree(prompt);
1758 xfree(answer);
1760 if(nbits<min || nbits>max)
1761 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1762 gcry_pk_algo_name (algo), min, max);
1763 else
1764 break;
1767 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1769 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
1771 nbits = ((nbits + 63) / 64) * 64;
1772 tty_printf(_("rounded up to %u bits\n"), nbits );
1774 else if( (nbits % 32) )
1776 nbits = ((nbits + 31) / 32) * 32;
1777 tty_printf(_("rounded up to %u bits\n"), nbits );
1780 return nbits;
1784 /****************
1785 * Parse an expire string and return its value in seconds.
1786 * Returns (u32)-1 on error.
1787 * This isn't perfect since scan_isodatestr returns unix time, and
1788 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1789 * Because of this, we only permit setting expirations up to 2106, but
1790 * OpenPGP could theoretically allow up to 2242. I think we'll all
1791 * just cope for the next few years until we get a 64-bit time_t or
1792 * similar.
1795 parse_expire_string( const char *string )
1797 int mult;
1798 u32 seconds;
1799 u32 abs_date = 0;
1800 u32 curtime = make_timestamp ();
1802 if (!*string)
1803 seconds = 0;
1804 else if (!strncmp (string, "seconds=", 8))
1805 seconds = atoi (string+8);
1806 else if ((abs_date = scan_isodatestr(string)) && abs_date > curtime)
1807 seconds = abs_date - curtime;
1808 else if ((mult = check_valid_days (string)))
1809 seconds = atoi (string) * 86400L * mult;
1810 else
1811 seconds = (u32)(-1);
1813 return seconds;
1816 /* Parsean Creation-Date string which is either "1986-04-26" or
1817 "19860426T042640". Returns 0 on error. */
1818 static u32
1819 parse_creation_string (const char *string)
1821 u32 seconds;
1823 if (!*string)
1824 seconds = 0;
1825 else if ( !strncmp (string, "seconds=", 8) )
1826 seconds = atoi (string+8);
1827 else if ( !(seconds = scan_isodatestr (string)))
1829 time_t tmp = isotime2epoch (string);
1830 seconds = (tmp == (time_t)(-1))? 0 : tmp;
1832 return seconds;
1836 /* object == 0 for a key, and 1 for a sig */
1838 ask_expire_interval(int object,const char *def_expire)
1840 u32 interval;
1841 char *answer;
1843 switch(object)
1845 case 0:
1846 if(def_expire)
1847 BUG();
1848 tty_printf(_("Please specify how long the key should be valid.\n"
1849 " 0 = key does not expire\n"
1850 " <n> = key expires in n days\n"
1851 " <n>w = key expires in n weeks\n"
1852 " <n>m = key expires in n months\n"
1853 " <n>y = key expires in n years\n"));
1854 break;
1856 case 1:
1857 if(!def_expire)
1858 BUG();
1859 tty_printf(_("Please specify how long the signature should be valid.\n"
1860 " 0 = signature does not expire\n"
1861 " <n> = signature expires in n days\n"
1862 " <n>w = signature expires in n weeks\n"
1863 " <n>m = signature expires in n months\n"
1864 " <n>y = signature expires in n years\n"));
1865 break;
1867 default:
1868 BUG();
1871 /* Note: The elgamal subkey for DSA has no expiration date because
1872 * it must be signed with the DSA key and this one has the expiration
1873 * date */
1875 answer = NULL;
1876 for(;;)
1878 u32 curtime=make_timestamp();
1880 xfree(answer);
1881 if(object==0)
1882 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1883 else
1885 char *prompt;
1887 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1888 /* This will actually end up larger than necessary because
1889 of the 2 bytes for '%s' */
1890 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
1891 sprintf(prompt,PROMPTSTRING,def_expire);
1892 #undef PROMPTSTRING
1894 answer = cpr_get("siggen.valid",prompt);
1895 xfree(prompt);
1897 if(*answer=='\0')
1898 answer=xstrdup(def_expire);
1900 cpr_kill_prompt();
1901 trim_spaces(answer);
1902 interval = parse_expire_string( answer );
1903 if( interval == (u32)-1 )
1905 tty_printf(_("invalid value\n"));
1906 continue;
1909 if( !interval )
1911 tty_printf((object==0)
1912 ? _("Key does not expire at all\n")
1913 : _("Signature does not expire at all\n"));
1915 else
1917 tty_printf(object==0
1918 ? _("Key expires at %s\n")
1919 : _("Signature expires at %s\n"),
1920 asctimestamp((ulong)(curtime + interval) ) );
1921 #if SIZEOF_TIME_T <= 4
1922 if ( (time_t)((ulong)(curtime+interval)) < 0 )
1923 tty_printf (_("Your system can't display dates beyond 2038.\n"
1924 "However, it will be correctly handled up to"
1925 " 2106.\n"));
1926 else
1927 #endif /*SIZEOF_TIME_T*/
1928 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
1930 tty_printf (_("invalid value\n"));
1931 continue;
1935 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1936 _("Is this correct? (y/N) ")) )
1937 break;
1940 xfree(answer);
1941 return interval;
1945 ask_expiredate()
1947 u32 x = ask_expire_interval(0,NULL);
1948 return x? make_timestamp() + x : 0;
1952 static char *
1953 ask_user_id( int mode )
1955 char *answer;
1956 char *aname, *acomment, *amail, *uid;
1958 if ( !mode )
1960 const char *s1 =
1961 N_("\n"
1962 "GnuPG needs to construct a user ID to identify your key.\n"
1963 "\n");
1964 const char *s2 = _(s1);
1966 if (!strcmp (s1, s2))
1968 /* There is no translation for the string thus we to use
1969 the old info text. gettext has no way to tell whether
1970 a translation is actually available, thus we need to
1971 to compare again. */
1972 const char *s3 = N_("\n"
1973 "You need a user ID to identify your key; "
1974 "the software constructs the user ID\n"
1975 "from the Real Name, Comment and Email Address in this form:\n"
1976 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
1977 const char *s4 = _(s3);
1978 if (strcmp (s3, s4))
1979 s2 = s3; /* A translation exists - use it. */
1981 tty_printf ("%s", s2) ;
1983 uid = aname = acomment = amail = NULL;
1984 for(;;) {
1985 char *p;
1986 int fail=0;
1988 if( !aname ) {
1989 for(;;) {
1990 xfree(aname);
1991 aname = cpr_get("keygen.name",_("Real name: "));
1992 trim_spaces(aname);
1993 cpr_kill_prompt();
1995 if( opt.allow_freeform_uid )
1996 break;
1998 if( strpbrk( aname, "<>" ) )
1999 tty_printf(_("Invalid character in name\n"));
2000 else if( digitp(aname) )
2001 tty_printf(_("Name may not start with a digit\n"));
2002 else if( strlen(aname) < 5 )
2003 tty_printf(_("Name must be at least 5 characters long\n"));
2004 else
2005 break;
2008 if( !amail ) {
2009 for(;;) {
2010 xfree(amail);
2011 amail = cpr_get("keygen.email",_("Email address: "));
2012 trim_spaces(amail);
2013 cpr_kill_prompt();
2014 if( !*amail || opt.allow_freeform_uid )
2015 break; /* no email address is okay */
2016 else if ( !is_valid_mailbox (amail) )
2017 tty_printf(_("Not a valid email address\n"));
2018 else
2019 break;
2022 if( !acomment ) {
2023 for(;;) {
2024 xfree(acomment);
2025 acomment = cpr_get("keygen.comment",_("Comment: "));
2026 trim_spaces(acomment);
2027 cpr_kill_prompt();
2028 if( !*acomment )
2029 break; /* no comment is okay */
2030 else if( strpbrk( acomment, "()" ) )
2031 tty_printf(_("Invalid character in comment\n"));
2032 else
2033 break;
2038 xfree(uid);
2039 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2040 p = stpcpy(p, aname );
2041 if( *acomment )
2042 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2043 if( *amail )
2044 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2046 /* Append a warning if the RNG is switched into fake mode. */
2047 if ( random_is_faked () )
2048 strcpy(p, " (insecure!)" );
2050 /* print a note in case that UTF8 mapping has to be done */
2051 for(p=uid; *p; p++ ) {
2052 if( *p & 0x80 ) {
2053 tty_printf(_("You are using the `%s' character set.\n"),
2054 get_native_charset() );
2055 break;
2059 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2060 /* fixme: add a warning if this user-id already exists */
2061 if( !*amail && !opt.allow_freeform_uid
2062 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2063 fail = 1;
2064 tty_printf(_("Please don't put the email address "
2065 "into the real name or the comment\n") );
2068 for(;;) {
2069 /* TRANSLATORS: These are the allowed answers in
2070 lower and uppercase. Below you will find the matching
2071 string which should be translated accordingly and the
2072 letter changed to match the one in the answer string.
2074 n = Change name
2075 c = Change comment
2076 e = Change email
2077 o = Okay (ready, continue)
2078 q = Quit
2080 const char *ansstr = _("NnCcEeOoQq");
2082 if( strlen(ansstr) != 10 )
2083 BUG();
2084 if( cpr_enabled() ) {
2085 answer = xstrdup(ansstr+6);
2086 answer[1] = 0;
2088 else {
2089 answer = cpr_get("keygen.userid.cmd", fail?
2090 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2091 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2092 cpr_kill_prompt();
2094 if( strlen(answer) > 1 )
2096 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2097 xfree(aname); aname = NULL;
2098 break;
2100 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2101 xfree(acomment); acomment = NULL;
2102 break;
2104 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2105 xfree(amail); amail = NULL;
2106 break;
2108 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2109 if( fail ) {
2110 tty_printf(_("Please correct the error first\n"));
2112 else {
2113 xfree(aname); aname = NULL;
2114 xfree(acomment); acomment = NULL;
2115 xfree(amail); amail = NULL;
2116 break;
2119 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2120 xfree(aname); aname = NULL;
2121 xfree(acomment); acomment = NULL;
2122 xfree(amail); amail = NULL;
2123 xfree(uid); uid = NULL;
2124 break;
2126 xfree(answer);
2128 xfree(answer);
2129 if( !amail && !acomment && !amail )
2130 break;
2131 xfree(uid); uid = NULL;
2133 if( uid ) {
2134 char *p = native_to_utf8( uid );
2135 xfree( uid );
2136 uid = p;
2138 return uid;
2142 static DEK *
2143 do_ask_passphrase ( STRING2KEY **ret_s2k, int *r_canceled )
2145 DEK *dek = NULL;
2146 STRING2KEY *s2k;
2147 const char *errtext = NULL;
2149 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2151 s2k = xmalloc_secure( sizeof *s2k );
2152 for(;;) {
2153 s2k->mode = opt.s2k_mode;
2154 s2k->hash_algo = S2K_DIGEST_ALGO;
2155 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k,2,
2156 errtext, r_canceled);
2157 if (!dek && *r_canceled) {
2158 xfree(dek); dek = NULL;
2159 xfree(s2k); s2k = NULL;
2160 break;
2162 else if( !dek ) {
2163 errtext = N_("passphrase not correctly repeated; try again");
2164 tty_printf(_("%s.\n"), _(errtext));
2166 else if( !dek->keylen ) {
2167 xfree(dek); dek = NULL;
2168 xfree(s2k); s2k = NULL;
2169 tty_printf(_(
2170 "You don't want a passphrase - this is probably a *bad* idea!\n"
2171 "I will do it anyway. You can change your passphrase at any time,\n"
2172 "using this program with the option \"--edit-key\".\n\n"));
2173 break;
2175 else
2176 break; /* okay */
2178 *ret_s2k = s2k;
2179 return dek;
2183 /* Basic key generation. Here we divert to the actual generation
2184 routines based on the requested algorithm. */
2185 static int
2186 do_create (int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
2187 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk,
2188 u32 timestamp, u32 expiredate, int is_subkey )
2190 int rc=0;
2192 if( !opt.batch )
2193 tty_printf(_(
2194 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2195 "some other action (type on the keyboard, move the mouse, utilize the\n"
2196 "disks) during the prime generation; this gives the random number\n"
2197 "generator a better chance to gain enough entropy.\n") );
2199 if( algo == PUBKEY_ALGO_ELGAMAL_E )
2200 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2201 timestamp, expiredate, is_subkey);
2202 else if( algo == PUBKEY_ALGO_DSA )
2203 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk,
2204 timestamp, expiredate, is_subkey);
2205 else if( algo == PUBKEY_ALGO_RSA )
2206 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2207 timestamp, expiredate, is_subkey);
2208 else
2209 BUG();
2211 return rc;
2215 /****************
2216 * Generate a new user id packet, or return NULL if canceled
2218 PKT_user_id *
2219 generate_user_id()
2221 PKT_user_id *uid;
2222 char *p;
2223 size_t n;
2225 p = ask_user_id( 1 );
2226 if( !p )
2227 return NULL;
2228 n = strlen(p);
2229 uid = xmalloc_clear( sizeof *uid + n );
2230 uid->len = n;
2231 strcpy(uid->name, p);
2232 uid->ref = 1;
2233 return uid;
2237 static void
2238 release_parameter_list( struct para_data_s *r )
2240 struct para_data_s *r2;
2242 for( ; r ; r = r2 ) {
2243 r2 = r->next;
2244 if( r->key == pPASSPHRASE_DEK )
2245 xfree( r->u.dek );
2246 else if( r->key == pPASSPHRASE_S2K )
2247 xfree( r->u.s2k );
2249 xfree(r);
2253 static struct para_data_s *
2254 get_parameter( struct para_data_s *para, enum para_name key )
2256 struct para_data_s *r;
2258 for( r = para; r && r->key != key; r = r->next )
2260 return r;
2263 static const char *
2264 get_parameter_value( struct para_data_s *para, enum para_name key )
2266 struct para_data_s *r = get_parameter( para, key );
2267 return (r && *r->u.value)? r->u.value : NULL;
2270 static int
2271 get_parameter_algo( struct para_data_s *para, enum para_name key )
2273 int i;
2274 struct para_data_s *r = get_parameter( para, key );
2275 if( !r )
2276 return -1;
2277 if( digitp( r->u.value ) )
2278 i = atoi( r->u.value );
2279 else if ( !strcmp ( r->u.value, "ELG-E")
2280 || !strcmp ( r->u.value, "ELG") )
2281 i = GCRY_PK_ELG_E;
2282 else
2283 i = gcry_pk_map_name (r->u.value);
2284 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2285 i = 0; /* we don't want to allow generation of these algorithms */
2286 return i;
2290 * parse the usage parameter and set the keyflags. Return true on error.
2292 static int
2293 parse_parameter_usage (const char *fname,
2294 struct para_data_s *para, enum para_name key)
2296 struct para_data_s *r = get_parameter( para, key );
2297 char *p, *pn;
2298 unsigned int use;
2300 if( !r )
2301 return 0; /* none (this is an optional parameter)*/
2303 use = 0;
2304 pn = r->u.value;
2305 while ( (p = strsep (&pn, " \t,")) ) {
2306 if ( !*p)
2308 else if ( !ascii_strcasecmp (p, "sign") )
2309 use |= PUBKEY_USAGE_SIG;
2310 else if ( !ascii_strcasecmp (p, "encrypt") )
2311 use |= PUBKEY_USAGE_ENC;
2312 else if ( !ascii_strcasecmp (p, "auth") )
2313 use |= PUBKEY_USAGE_AUTH;
2314 else {
2315 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2316 return -1; /* error */
2319 r->u.usage = use;
2320 return 1;
2323 static int
2324 parse_revocation_key (const char *fname,
2325 struct para_data_s *para, enum para_name key)
2327 struct para_data_s *r = get_parameter( para, key );
2328 struct revocation_key revkey;
2329 char *pn;
2330 int i;
2332 if( !r )
2333 return 0; /* none (this is an optional parameter) */
2335 pn = r->u.value;
2337 revkey.class=0x80;
2338 revkey.algid=atoi(pn);
2339 if(!revkey.algid)
2340 goto fail;
2342 /* Skip to the fpr */
2343 while(*pn && *pn!=':')
2344 pn++;
2346 if(*pn!=':')
2347 goto fail;
2349 pn++;
2351 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2353 int c=hextobyte(pn);
2354 if(c==-1)
2355 goto fail;
2357 revkey.fpr[i]=c;
2360 /* skip to the tag */
2361 while(*pn && *pn!='s' && *pn!='S')
2362 pn++;
2364 if(ascii_strcasecmp(pn,"sensitive")==0)
2365 revkey.class|=0x40;
2367 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2369 return 0;
2371 fail:
2372 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2373 return -1; /* error */
2377 static u32
2378 get_parameter_u32( struct para_data_s *para, enum para_name key )
2380 struct para_data_s *r = get_parameter( para, key );
2382 if( !r )
2383 return 0;
2384 if( r->key == pKEYCREATIONDATE )
2385 return r->u.creation;
2386 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2387 return r->u.expire;
2388 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2389 return r->u.usage;
2391 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2394 static unsigned int
2395 get_parameter_uint( struct para_data_s *para, enum para_name key )
2397 return get_parameter_u32( para, key );
2400 static DEK *
2401 get_parameter_dek( struct para_data_s *para, enum para_name key )
2403 struct para_data_s *r = get_parameter( para, key );
2404 return r? r->u.dek : NULL;
2407 static STRING2KEY *
2408 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2410 struct para_data_s *r = get_parameter( para, key );
2411 return r? r->u.s2k : NULL;
2414 static struct revocation_key *
2415 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2417 struct para_data_s *r = get_parameter( para, key );
2418 return r? &r->u.revkey : NULL;
2421 static int
2422 proc_parameter_file( struct para_data_s *para, const char *fname,
2423 struct output_control_s *outctrl, int card )
2425 struct para_data_s *r;
2426 const char *s1, *s2, *s3;
2427 size_t n;
2428 char *p;
2429 int have_user_id=0,err,algo;
2431 /* Check that we have all required parameters. */
2432 r = get_parameter( para, pKEYTYPE );
2433 if(r)
2435 algo=get_parameter_algo(para,pKEYTYPE);
2436 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2438 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
2439 return -1;
2442 else
2444 log_error("%s: no Key-Type specified\n",fname);
2445 return -1;
2448 err=parse_parameter_usage (fname, para, pKEYUSAGE);
2449 if(err==0)
2451 /* Default to algo capabilities if key-usage is not provided */
2452 r=xmalloc_clear(sizeof(*r));
2453 r->key=pKEYUSAGE;
2454 r->u.usage=openpgp_pk_algo_usage(algo);
2455 r->next=para;
2456 para=r;
2458 else if(err==-1)
2459 return -1;
2461 r = get_parameter( para, pSUBKEYTYPE );
2462 if(r)
2464 algo=get_parameter_algo( para, pSUBKEYTYPE);
2465 if (openpgp_pk_test_algo (algo))
2467 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
2468 return -1;
2471 err=parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2472 if(err==0)
2474 /* Default to algo capabilities if subkey-usage is not
2475 provided */
2476 r=xmalloc_clear(sizeof(*r));
2477 r->key=pSUBKEYUSAGE;
2478 r->u.usage=openpgp_pk_algo_usage(algo);
2479 r->next=para;
2480 para=r;
2482 else if(err==-1)
2483 return -1;
2486 if( get_parameter_value( para, pUSERID ) )
2487 have_user_id=1;
2488 else
2490 /* create the formatted user ID */
2491 s1 = get_parameter_value( para, pNAMEREAL );
2492 s2 = get_parameter_value( para, pNAMECOMMENT );
2493 s3 = get_parameter_value( para, pNAMEEMAIL );
2494 if( s1 || s2 || s3 )
2496 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2497 r = xmalloc_clear( sizeof *r + n + 20 );
2498 r->key = pUSERID;
2499 p = r->u.value;
2500 if( s1 )
2501 p = stpcpy(p, s1 );
2502 if( s2 )
2503 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2504 if( s3 )
2505 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2506 r->next = para;
2507 para = r;
2508 have_user_id=1;
2512 if(!have_user_id)
2514 log_error("%s: no User-ID specified\n",fname);
2515 return -1;
2518 /* Set preferences, if any. */
2519 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2521 /* Set keyserver, if any. */
2522 s1=get_parameter_value( para, pKEYSERVER );
2523 if(s1)
2525 struct keyserver_spec *spec;
2527 spec=parse_keyserver_uri(s1,1,NULL,0);
2528 if(spec)
2530 free_keyserver_spec(spec);
2531 opt.def_keyserver_url=s1;
2533 else
2535 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2536 return -1;
2540 /* Set revoker, if any. */
2541 if (parse_revocation_key (fname, para, pREVOKER))
2542 return -1;
2544 /* Make DEK and S2K from the Passphrase. */
2545 if (outctrl->ask_passphrase)
2547 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2548 feature is required so that GUIs are able to do a key
2549 creation but have gpg-agent ask for the passphrase. */
2550 int canceled = 0;
2551 STRING2KEY *s2k;
2552 DEK *dek;
2554 dek = do_ask_passphrase ( &s2k, &canceled );
2555 if (dek)
2557 r = xmalloc_clear( sizeof *r );
2558 r->key = pPASSPHRASE_DEK;
2559 r->u.dek = dek;
2560 r->next = para;
2561 para = r;
2562 r = xmalloc_clear( sizeof *r );
2563 r->key = pPASSPHRASE_S2K;
2564 r->u.s2k = s2k;
2565 r->next = para;
2566 para = r;
2569 if (canceled)
2571 log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
2572 return -1;
2575 else
2577 r = get_parameter( para, pPASSPHRASE );
2578 if ( r && *r->u.value )
2580 /* We have a plain text passphrase - create a DEK from it.
2581 * It is a little bit ridiculous to keep it in secure memory
2582 * but because we do this always, why not here. */
2583 STRING2KEY *s2k;
2584 DEK *dek;
2586 s2k = xmalloc_secure ( sizeof *s2k );
2587 s2k->mode = opt.s2k_mode;
2588 s2k->hash_algo = S2K_DIGEST_ALGO;
2589 set_next_passphrase ( r->u.value );
2590 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2591 NULL, NULL);
2592 set_next_passphrase (NULL );
2593 assert (dek);
2594 memset (r->u.value, 0, strlen(r->u.value));
2596 r = xmalloc_clear (sizeof *r);
2597 r->key = pPASSPHRASE_S2K;
2598 r->u.s2k = s2k;
2599 r->next = para;
2600 para = r;
2601 r = xmalloc_clear (sizeof *r);
2602 r->key = pPASSPHRASE_DEK;
2603 r->u.dek = dek;
2604 r->next = para;
2605 para = r;
2609 /* Make KEYCREATIONDATE from Creation-Date. */
2610 r = get_parameter (para, pCREATIONDATE);
2611 if (r && *r->u.value)
2613 u32 seconds;
2615 seconds = parse_creation_string (r->u.value);
2616 if (!seconds)
2618 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2619 return -1;
2621 r->u.creation = seconds;
2622 r->key = pKEYCREATIONDATE; /* Change that entry. */
2625 /* Make KEYEXPIRE from Expire-Date. */
2626 r = get_parameter( para, pEXPIREDATE );
2627 if( r && *r->u.value )
2629 u32 seconds;
2631 seconds = parse_expire_string( r->u.value );
2632 if( seconds == (u32)-1 )
2634 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2635 return -1;
2637 r->u.expire = seconds;
2638 r->key = pKEYEXPIRE; /* change hat entry */
2639 /* also set it for the subkey */
2640 r = xmalloc_clear( sizeof *r + 20 );
2641 r->key = pSUBKEYEXPIRE;
2642 r->u.expire = seconds;
2643 r->next = para;
2644 para = r;
2647 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2648 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2649 return -1;
2652 do_generate_keypair( para, outctrl, card );
2653 return 0;
2657 /****************
2658 * Kludge to allow non interactive key generation controlled
2659 * by a parameter file.
2660 * Note, that string parameters are expected to be in UTF-8
2662 static void
2663 read_parameter_file( const char *fname )
2665 static struct { const char *name;
2666 enum para_name key;
2667 } keywords[] = {
2668 { "Key-Type", pKEYTYPE},
2669 { "Key-Length", pKEYLENGTH },
2670 { "Key-Usage", pKEYUSAGE },
2671 { "Subkey-Type", pSUBKEYTYPE },
2672 { "Subkey-Length", pSUBKEYLENGTH },
2673 { "Subkey-Usage", pSUBKEYUSAGE },
2674 { "Name-Real", pNAMEREAL },
2675 { "Name-Email", pNAMEEMAIL },
2676 { "Name-Comment", pNAMECOMMENT },
2677 { "Expire-Date", pEXPIREDATE },
2678 { "Creation-Date", pCREATIONDATE },
2679 { "Passphrase", pPASSPHRASE },
2680 { "Preferences", pPREFERENCES },
2681 { "Revoker", pREVOKER },
2682 { "Handle", pHANDLE },
2683 { "Keyserver", pKEYSERVER },
2684 { NULL, 0 }
2686 IOBUF fp;
2687 byte *line;
2688 unsigned int maxlen, nline;
2689 char *p;
2690 int lnr;
2691 const char *err = NULL;
2692 struct para_data_s *para, *r;
2693 int i;
2694 struct output_control_s outctrl;
2696 memset( &outctrl, 0, sizeof( outctrl ) );
2697 outctrl.pub.afx = new_armor_context ();
2698 outctrl.sec.afx = new_armor_context ();
2700 if( !fname || !*fname)
2701 fname = "-";
2703 fp = iobuf_open (fname);
2704 if (fp && is_secured_file (iobuf_get_fd (fp)))
2706 iobuf_close (fp);
2707 fp = NULL;
2708 errno = EPERM;
2710 if (!fp) {
2711 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2712 return;
2714 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2716 lnr = 0;
2717 err = NULL;
2718 para = NULL;
2719 maxlen = 1024;
2720 line = NULL;
2721 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2722 char *keyword, *value;
2724 lnr++;
2725 if( !maxlen ) {
2726 err = "line too long";
2727 break;
2729 for( p = line; isspace(*(byte*)p); p++ )
2731 if( !*p || *p == '#' )
2732 continue;
2733 keyword = p;
2734 if( *keyword == '%' ) {
2735 for( ; !isspace(*(byte*)p); p++ )
2737 if( *p )
2738 *p++ = 0;
2739 for( ; isspace(*(byte*)p); p++ )
2741 value = p;
2742 trim_trailing_ws( value, strlen(value) );
2743 if( !ascii_strcasecmp( keyword, "%echo" ) )
2744 log_info("%s\n", value );
2745 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2746 outctrl.dryrun = 1;
2747 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
2748 outctrl.ask_passphrase = 1;
2749 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
2750 outctrl.ask_passphrase = 0;
2751 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2752 outctrl.lnr = lnr;
2753 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2754 print_status_key_not_created
2755 (get_parameter_value (para, pHANDLE));
2756 release_parameter_list( para );
2757 para = NULL;
2759 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2760 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2761 ; /* still the same file - ignore it */
2762 else {
2763 xfree( outctrl.pub.newfname );
2764 outctrl.pub.newfname = xstrdup( value );
2765 outctrl.use_files = 1;
2768 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2769 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2770 ; /* still the same file - ignore it */
2771 else {
2772 xfree( outctrl.sec.newfname );
2773 outctrl.sec.newfname = xstrdup( value );
2774 outctrl.use_files = 1;
2777 else
2778 log_info("skipping control `%s' (%s)\n", keyword, value );
2781 continue;
2785 if( !(p = strchr( p, ':' )) || p == keyword ) {
2786 err = "missing colon";
2787 break;
2789 if( *p )
2790 *p++ = 0;
2791 for( ; isspace(*(byte*)p); p++ )
2793 if( !*p ) {
2794 err = "missing argument";
2795 break;
2797 value = p;
2798 trim_trailing_ws( value, strlen(value) );
2800 for(i=0; keywords[i].name; i++ ) {
2801 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2802 break;
2804 if( !keywords[i].name ) {
2805 err = "unknown keyword";
2806 break;
2808 if( keywords[i].key != pKEYTYPE && !para ) {
2809 err = "parameter block does not start with \"Key-Type\"";
2810 break;
2813 if( keywords[i].key == pKEYTYPE && para ) {
2814 outctrl.lnr = lnr;
2815 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2816 print_status_key_not_created
2817 (get_parameter_value (para, pHANDLE));
2818 release_parameter_list( para );
2819 para = NULL;
2821 else {
2822 for( r = para; r; r = r->next ) {
2823 if( r->key == keywords[i].key )
2824 break;
2826 if( r ) {
2827 err = "duplicate keyword";
2828 break;
2831 r = xmalloc_clear( sizeof *r + strlen( value ) );
2832 r->lnr = lnr;
2833 r->key = keywords[i].key;
2834 strcpy( r->u.value, value );
2835 r->next = para;
2836 para = r;
2838 if( err )
2839 log_error("%s:%d: %s\n", fname, lnr, err );
2840 else if( iobuf_error (fp) ) {
2841 log_error("%s:%d: read error\n", fname, lnr);
2843 else if( para ) {
2844 outctrl.lnr = lnr;
2845 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2846 print_status_key_not_created (get_parameter_value (para, pHANDLE));
2849 if( outctrl.use_files ) { /* close open streams */
2850 iobuf_close( outctrl.pub.stream );
2851 iobuf_close( outctrl.sec.stream );
2853 /* Must invalidate that ugly cache to actually close it. */
2854 if (outctrl.pub.fname)
2855 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
2856 if (outctrl.sec.fname)
2857 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
2859 xfree( outctrl.pub.fname );
2860 xfree( outctrl.pub.newfname );
2861 xfree( outctrl.sec.fname );
2862 xfree( outctrl.sec.newfname );
2865 release_parameter_list( para );
2866 iobuf_close (fp);
2867 release_armor_context (outctrl.pub.afx);
2868 release_armor_context (outctrl.sec.afx);
2873 * Generate a keypair (fname is only used in batch mode) If
2874 * CARD_SERIALNO is not NULL the function will create the keys on an
2875 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2876 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2877 * generate in software, imported to the card and a backup file
2878 * written to directory given by this argument .
2880 void
2881 generate_keypair (const char *fname, const char *card_serialno,
2882 const char *backup_encryption_dir)
2884 unsigned int nbits;
2885 char *uid = NULL;
2886 DEK *dek;
2887 STRING2KEY *s2k;
2888 int algo;
2889 unsigned int use;
2890 int both = 0;
2891 u32 expire;
2892 struct para_data_s *para = NULL;
2893 struct para_data_s *r;
2894 struct output_control_s outctrl;
2895 int canceled;
2897 memset( &outctrl, 0, sizeof( outctrl ) );
2899 if (opt.batch && card_serialno)
2901 /* We don't yet support unattended key generation. */
2902 log_error (_("can't do this in batch mode\n"));
2903 return;
2906 if (opt.batch)
2908 read_parameter_file( fname );
2909 return;
2912 if (card_serialno)
2914 #ifdef ENABLE_CARD_SUPPORT
2915 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
2916 r->key = pSERIALNO;
2917 strcpy( r->u.value, card_serialno);
2918 r->next = para;
2919 para = r;
2921 algo = PUBKEY_ALGO_RSA;
2923 r = xcalloc (1, sizeof *r + 20 );
2924 r->key = pKEYTYPE;
2925 sprintf( r->u.value, "%d", algo );
2926 r->next = para;
2927 para = r;
2928 r = xcalloc (1, sizeof *r + 20 );
2929 r->key = pKEYUSAGE;
2930 strcpy (r->u.value, "sign");
2931 r->next = para;
2932 para = r;
2934 r = xcalloc (1, sizeof *r + 20 );
2935 r->key = pSUBKEYTYPE;
2936 sprintf( r->u.value, "%d", algo );
2937 r->next = para;
2938 para = r;
2939 r = xcalloc (1, sizeof *r + 20 );
2940 r->key = pSUBKEYUSAGE;
2941 strcpy (r->u.value, "encrypt");
2942 r->next = para;
2943 para = r;
2945 r = xcalloc (1, sizeof *r + 20 );
2946 r->key = pAUTHKEYTYPE;
2947 sprintf( r->u.value, "%d", algo );
2948 r->next = para;
2949 para = r;
2951 if (backup_encryption_dir)
2953 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
2954 r->key = pBACKUPENCDIR;
2955 strcpy (r->u.value, backup_encryption_dir);
2956 r->next = para;
2957 para = r;
2959 #endif /*ENABLE_CARD_SUPPORT*/
2961 else
2963 algo = ask_algo( 0, &use );
2964 if( !algo )
2965 { /* default: DSA with ElG subkey of the specified size */
2966 both = 1;
2967 r = xmalloc_clear( sizeof *r + 20 );
2968 r->key = pKEYTYPE;
2969 sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
2970 r->next = para;
2971 para = r;
2972 nbits = ask_keysize( PUBKEY_ALGO_DSA );
2973 r = xmalloc_clear( sizeof *r + 20 );
2974 r->key = pKEYLENGTH;
2975 sprintf( r->u.value, "%u", nbits);
2976 r->next = para;
2977 para = r;
2978 r = xmalloc_clear( sizeof *r + 20 );
2979 r->key = pKEYUSAGE;
2980 strcpy( r->u.value, "sign" );
2981 r->next = para;
2982 para = r;
2984 algo = PUBKEY_ALGO_ELGAMAL_E;
2985 r = xmalloc_clear( sizeof *r + 20 );
2986 r->key = pSUBKEYTYPE;
2987 sprintf( r->u.value, "%d", algo );
2988 r->next = para;
2989 para = r;
2990 r = xmalloc_clear( sizeof *r + 20 );
2991 r->key = pSUBKEYUSAGE;
2992 strcpy( r->u.value, "encrypt" );
2993 r->next = para;
2994 para = r;
2996 else
2998 r = xmalloc_clear( sizeof *r + 20 );
2999 r->key = pKEYTYPE;
3000 sprintf( r->u.value, "%d", algo );
3001 r->next = para;
3002 para = r;
3004 if (use)
3006 r = xmalloc_clear( sizeof *r + 25 );
3007 r->key = pKEYUSAGE;
3008 sprintf( r->u.value, "%s%s%s",
3009 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3010 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3011 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3012 r->next = para;
3013 para = r;
3018 nbits = ask_keysize( algo );
3019 r = xmalloc_clear( sizeof *r + 20 );
3020 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3021 sprintf( r->u.value, "%u", nbits);
3022 r->next = para;
3023 para = r;
3026 expire = ask_expire_interval(0,NULL);
3027 r = xmalloc_clear( sizeof *r + 20 );
3028 r->key = pKEYEXPIRE;
3029 r->u.expire = expire;
3030 r->next = para;
3031 para = r;
3032 r = xmalloc_clear( sizeof *r + 20 );
3033 r->key = pSUBKEYEXPIRE;
3034 r->u.expire = expire;
3035 r->next = para;
3036 para = r;
3038 uid = ask_user_id(0);
3039 if( !uid )
3041 log_error(_("Key generation canceled.\n"));
3042 release_parameter_list( para );
3043 return;
3045 r = xmalloc_clear( sizeof *r + strlen(uid) );
3046 r->key = pUSERID;
3047 strcpy( r->u.value, uid );
3048 r->next = para;
3049 para = r;
3051 canceled = 0;
3052 dek = card_serialno? NULL : do_ask_passphrase ( &s2k, &canceled );
3053 if( dek )
3055 r = xmalloc_clear( sizeof *r );
3056 r->key = pPASSPHRASE_DEK;
3057 r->u.dek = dek;
3058 r->next = para;
3059 para = r;
3060 r = xmalloc_clear( sizeof *r );
3061 r->key = pPASSPHRASE_S2K;
3062 r->u.s2k = s2k;
3063 r->next = para;
3064 para = r;
3067 if (canceled)
3068 log_error (_("Key generation canceled.\n"));
3069 else
3070 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3071 release_parameter_list( para );
3075 #ifdef ENABLE_CARD_SUPPORT
3076 /* Generate a raw key and return it as a secret key packet. The
3077 function will ask for the passphrase and return a protected as well
3078 as an unprotected copy of a new secret key packet. 0 is returned
3079 on success and the caller must then free the returned values. */
3080 static int
3081 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3082 PKT_secret_key **r_sk_unprotected,
3083 PKT_secret_key **r_sk_protected)
3085 int rc;
3086 DEK *dek = NULL;
3087 STRING2KEY *s2k = NULL;
3088 PKT_secret_key *sk = NULL;
3089 int i;
3090 size_t nskey, npkey;
3091 gcry_sexp_t s_parms, s_key;
3092 int canceled;
3094 npkey = pubkey_get_npkey (algo);
3095 nskey = pubkey_get_nskey (algo);
3096 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3098 if (nbits < 512)
3100 nbits = 512;
3101 log_info (_("keysize invalid; using %u bits\n"), nbits );
3104 if ((nbits % 32))
3106 nbits = ((nbits + 31) / 32) * 32;
3107 log_info(_("keysize rounded up to %u bits\n"), nbits );
3110 dek = do_ask_passphrase (&s2k, &canceled);
3111 if (canceled)
3113 rc = gpg_error (GPG_ERR_CANCELED);
3114 goto leave;
3117 sk = xmalloc_clear (sizeof *sk);
3118 sk->timestamp = created_at;
3119 sk->version = 4;
3120 sk->pubkey_algo = algo;
3122 if ( !is_RSA (algo) )
3124 log_error ("only RSA is supported for offline generated keys\n");
3125 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3126 goto leave;
3128 rc = gcry_sexp_build (&s_parms, NULL,
3129 "(genkey(rsa(nbits %d)))",
3130 (int)nbits);
3131 if (rc)
3132 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3133 rc = gcry_pk_genkey (&s_key, s_parms);
3134 gcry_sexp_release (s_parms);
3135 if (rc)
3137 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3138 goto leave;
3140 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3141 gcry_sexp_release (s_key);
3142 if (rc)
3144 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3145 goto leave;
3148 for (i=npkey; i < nskey; i++)
3149 sk->csum += checksum_mpi (sk->skey[i]);
3151 if (r_sk_unprotected)
3152 *r_sk_unprotected = copy_secret_key (NULL, sk);
3154 rc = genhelp_protect (dek, s2k, sk);
3155 if (rc)
3156 goto leave;
3158 if (r_sk_protected)
3160 *r_sk_protected = sk;
3161 sk = NULL;
3164 leave:
3165 if (sk)
3166 free_secret_key (sk);
3167 xfree (dek);
3168 xfree (s2k);
3169 return rc;
3171 #endif /* ENABLE_CARD_SUPPORT */
3173 /* Create and delete a dummy packet to start off a list of kbnodes. */
3174 static void
3175 start_tree(KBNODE *tree)
3177 PACKET *pkt;
3179 pkt=xmalloc_clear(sizeof(*pkt));
3180 pkt->pkttype=PKT_NONE;
3181 *tree=new_kbnode(pkt);
3182 delete_kbnode(*tree);
3186 static void
3187 do_generate_keypair (struct para_data_s *para,
3188 struct output_control_s *outctrl, int card)
3190 KBNODE pub_root = NULL;
3191 KBNODE sec_root = NULL;
3192 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3193 const char *s;
3194 struct revocation_key *revkey;
3195 int rc;
3196 int did_sub = 0;
3197 u32 timestamp;
3199 if( outctrl->dryrun )
3201 log_info("dry-run mode - key generation skipped\n");
3202 return;
3205 if ( outctrl->use_files )
3207 if ( outctrl->pub.newfname )
3209 iobuf_close(outctrl->pub.stream);
3210 outctrl->pub.stream = NULL;
3211 if (outctrl->pub.fname)
3212 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3213 xfree( outctrl->pub.fname );
3214 outctrl->pub.fname = outctrl->pub.newfname;
3215 outctrl->pub.newfname = NULL;
3217 if (is_secured_filename (outctrl->pub.fname) )
3219 outctrl->pub.stream = NULL;
3220 errno = EPERM;
3222 else
3223 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3224 if (!outctrl->pub.stream)
3226 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3227 strerror(errno) );
3228 return;
3230 if (opt.armor)
3232 outctrl->pub.afx->what = 1;
3233 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3236 if (outctrl->sec.newfname)
3238 mode_t oldmask;
3240 iobuf_close(outctrl->sec.stream);
3241 outctrl->sec.stream = NULL;
3242 if (outctrl->sec.fname)
3243 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3244 xfree( outctrl->sec.fname );
3245 outctrl->sec.fname = outctrl->sec.newfname;
3246 outctrl->sec.newfname = NULL;
3248 oldmask = umask (077);
3249 if (is_secured_filename (outctrl->sec.fname) )
3251 outctrl->sec.stream = NULL;
3252 errno = EPERM;
3254 else
3255 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3256 umask (oldmask);
3257 if (!outctrl->sec.stream)
3259 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3260 strerror(errno) );
3261 return;
3263 if (opt.armor)
3265 outctrl->sec.afx->what = 5;
3266 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3269 assert( outctrl->pub.stream );
3270 assert( outctrl->sec.stream );
3271 if (opt.verbose)
3273 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3274 if (card)
3275 log_info (_("writing secret key stub to `%s'\n"),
3276 outctrl->sec.fname);
3277 else
3278 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3283 /* We create the packets as a tree of kbnodes. Because the
3284 structure we create is known in advance we simply generate a
3285 linked list. The first packet is a dummy packet which we flag as
3286 deleted. The very first packet must always be a KEY packet. */
3288 start_tree (&pub_root);
3289 start_tree (&sec_root);
3291 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3292 if (!timestamp)
3293 timestamp = make_timestamp ();
3295 if (!card)
3297 rc = do_create (get_parameter_algo( para, pKEYTYPE ),
3298 get_parameter_uint( para, pKEYLENGTH ),
3299 pub_root, sec_root,
3300 get_parameter_dek( para, pPASSPHRASE_DEK ),
3301 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3302 &pri_sk,
3303 timestamp,
3304 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3306 else
3308 /* Note, that depending on the backend, the card key generation
3309 may update TIMESTAMP. */
3310 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3311 &timestamp,
3312 get_parameter_u32 (para, pKEYEXPIRE), para);
3313 if (!rc)
3315 pri_sk = sec_root->next->pkt->pkt.secret_key;
3316 assert (pri_sk);
3320 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3322 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3323 if (!rc)
3324 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3327 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3329 write_uid (pub_root, s );
3330 write_uid (sec_root, s );
3332 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3333 get_parameter_uint (para, pKEYUSAGE), timestamp);
3336 /* Write the auth key to the card before the encryption key. This
3337 is a partial workaround for a PGP bug (as of this writing, all
3338 versions including 8.1), that causes it to try and encrypt to
3339 the most recent subkey regardless of whether that subkey is
3340 actually an encryption type. In this case, the auth key is an
3341 RSA key so it succeeds. */
3343 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3345 /* Note, that depending on the backend, the card key generation
3346 may update TIMESTAMP. */
3347 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3348 &timestamp,
3349 get_parameter_u32 (para, pKEYEXPIRE), para);
3351 if (!rc)
3352 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3353 PUBKEY_USAGE_AUTH, timestamp);
3354 if (!rc)
3355 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3356 PUBKEY_USAGE_AUTH, timestamp);
3359 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3361 if (!card)
3363 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
3364 get_parameter_uint( para, pSUBKEYLENGTH ),
3365 pub_root, sec_root,
3366 get_parameter_dek( para, pPASSPHRASE_DEK ),
3367 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3368 &sub_sk,
3369 timestamp,
3370 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3372 else
3374 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3376 /* A backup of the encryption key has been requested.
3377 Generate the key in software and import it then to
3378 the card. Write a backup file. */
3379 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3380 pub_root, sec_root,
3381 timestamp,
3382 get_parameter_u32 (para,
3383 pKEYEXPIRE),
3384 para, s);
3386 else
3388 /* Note, that depending on the backend, the card key
3389 generation may update TIMESTAMP. */
3390 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3391 NULL,
3392 &timestamp,
3393 get_parameter_u32 (para, pKEYEXPIRE), para);
3397 if( !rc )
3398 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3399 get_parameter_uint (para, pSUBKEYUSAGE),
3400 timestamp);
3401 if( !rc )
3402 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3403 get_parameter_uint (para, pSUBKEYUSAGE),
3404 timestamp);
3405 did_sub = 1;
3408 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3410 rc = write_keyblock( outctrl->pub.stream, pub_root );
3411 if (rc)
3412 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3413 if (!rc)
3415 rc = write_keyblock( outctrl->sec.stream, sec_root );
3416 if(rc)
3417 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3420 else if (!rc) /* Write to the standard keyrings. */
3422 KEYDB_HANDLE pub_hd = keydb_new (0);
3423 KEYDB_HANDLE sec_hd = keydb_new (1);
3425 rc = keydb_locate_writable (pub_hd, NULL);
3426 if (rc)
3427 log_error (_("no writable public keyring found: %s\n"),
3428 g10_errstr (rc));
3430 if (!rc)
3432 rc = keydb_locate_writable (sec_hd, NULL);
3433 if (rc)
3434 log_error (_("no writable secret keyring found: %s\n"),
3435 g10_errstr (rc));
3438 if (!rc && opt.verbose)
3440 log_info (_("writing public key to `%s'\n"),
3441 keydb_get_resource_name (pub_hd));
3442 if (card)
3443 log_info (_("writing secret key stub to `%s'\n"),
3444 keydb_get_resource_name (sec_hd));
3445 else
3446 log_info (_("writing secret key to `%s'\n"),
3447 keydb_get_resource_name (sec_hd));
3450 if (!rc)
3452 rc = keydb_insert_keyblock (pub_hd, pub_root);
3453 if (rc)
3454 log_error (_("error writing public keyring `%s': %s\n"),
3455 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3458 if (!rc)
3460 rc = keydb_insert_keyblock (sec_hd, sec_root);
3461 if (rc)
3462 log_error (_("error writing secret keyring `%s': %s\n"),
3463 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3466 keydb_release (pub_hd);
3467 keydb_release (sec_hd);
3469 if (!rc)
3471 int no_enc_rsa;
3472 PKT_public_key *pk;
3474 no_enc_rsa = (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
3475 && get_parameter_uint (para, pKEYUSAGE)
3476 && !((get_parameter_uint (para, pKEYUSAGE)
3477 & PUBKEY_USAGE_ENC)) );
3479 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3481 keyid_from_pk(pk,pk->main_keyid);
3482 register_trusted_keyid(pk->main_keyid);
3484 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3485 | TRUST_ULTIMATE ));
3487 if (!opt.batch)
3489 tty_printf (_("public and secret key created and signed.\n") );
3490 tty_printf ("\n");
3491 list_keyblock(pub_root,0,1,NULL);
3495 if (!opt.batch
3496 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
3497 || no_enc_rsa )
3498 && !get_parameter (para, pSUBKEYTYPE) )
3500 tty_printf(_("Note that this key cannot be used for "
3501 "encryption. You may want to use\n"
3502 "the command \"--edit-key\" to generate a "
3503 "subkey for this purpose.\n") );
3508 if (rc)
3510 if (opt.batch)
3511 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3512 else
3513 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3514 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3516 else
3518 PKT_public_key *pk = find_kbnode (pub_root,
3519 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3520 print_status_key_created (did_sub? 'B':'P', pk,
3521 get_parameter_value (para, pHANDLE));
3523 release_kbnode( pub_root );
3524 release_kbnode( sec_root );
3526 if (pri_sk && !card) /* The unprotected secret key unless we */
3527 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3528 if (sub_sk)
3529 free_secret_key(sub_sk);
3533 /* Add a new subkey to an existing key. Returns true if a new key has
3534 been generated and put into the keyblocks. */
3536 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3538 int okay=0, rc=0;
3539 KBNODE node;
3540 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3541 int algo;
3542 unsigned int use;
3543 u32 expire;
3544 unsigned nbits;
3545 char *passphrase = NULL;
3546 DEK *dek = NULL;
3547 STRING2KEY *s2k = NULL;
3548 u32 cur_time;
3549 int ask_pass = 0;
3550 int canceled;
3552 /* Break out the primary secret key. */
3553 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3554 if( !node )
3556 log_error ("Oops; secret key not found anymore!\n");
3557 goto leave;
3560 /* Make a copy of the sk to keep the protected one in the keyblock. */
3561 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3563 cur_time = make_timestamp();
3565 if (pri_sk->timestamp > cur_time)
3567 ulong d = pri_sk->timestamp - cur_time;
3568 log_info ( d==1 ? _("key has been created %lu second "
3569 "in future (time warp or clock problem)\n")
3570 : _("key has been created %lu seconds "
3571 "in future (time warp or clock problem)\n"), d );
3572 if (!opt.ignore_time_conflict)
3574 rc = G10ERR_TIME_CONFLICT;
3575 goto leave;
3579 if (pri_sk->version < 4)
3581 log_info (_("NOTE: creating subkeys for v3 keys "
3582 "is not OpenPGP compliant\n"));
3583 goto leave;
3586 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3588 tty_printf (_("Secret parts of primary key are not available.\n"));
3589 rc = G10ERR_NO_SECKEY;
3590 goto leave;
3594 /* Unprotect to get the passphrase. */
3595 switch (is_secret_key_protected (pri_sk) )
3597 case -1:
3598 rc = G10ERR_PUBKEY_ALGO;
3599 break;
3600 case 0:
3601 tty_printf (_("This key is not protected.\n"));
3602 break;
3603 case -2:
3604 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3605 ask_pass = 1;
3606 break;
3607 default:
3608 tty_printf (_("Key is protected.\n"));
3609 rc = check_secret_key ( pri_sk, 0 );
3610 if (!rc)
3611 passphrase = get_last_passphrase();
3612 break;
3614 if (rc)
3615 goto leave;
3617 algo = ask_algo (1, &use);
3618 assert (algo);
3619 nbits = ask_keysize (algo);
3620 expire = ask_expire_interval (0, NULL);
3621 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3622 _("Really create? (y/N) ")))
3623 goto leave;
3625 canceled = 0;
3626 if (ask_pass)
3627 dek = do_ask_passphrase (&s2k, &canceled);
3628 else if (passphrase)
3630 s2k = xmalloc_secure ( sizeof *s2k );
3631 s2k->mode = opt.s2k_mode;
3632 s2k->hash_algo = S2K_DIGEST_ALGO;
3633 set_next_passphrase ( passphrase );
3634 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3635 NULL, NULL );
3638 if (canceled)
3639 rc = GPG_ERR_CANCELED;
3641 if (!rc)
3642 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3643 dek, s2k, &sub_sk, cur_time, expire, 1 );
3644 if (!rc)
3645 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3646 use, cur_time);
3647 if (!rc)
3648 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3649 use, cur_time);
3650 if (!rc)
3652 okay = 1;
3653 write_status_text (STATUS_KEY_CREATED, "S");
3656 leave:
3657 if (rc)
3658 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3659 xfree (passphrase);
3660 xfree (dek);
3661 xfree (s2k);
3662 /* Release the copy of the (now unprotected) secret keys. */
3663 if (pri_sk)
3664 free_secret_key (pri_sk);
3665 if (sub_sk)
3666 free_secret_key (sub_sk);
3667 set_next_passphrase (NULL);
3668 return okay;
3672 #ifdef ENABLE_CARD_SUPPORT
3673 /* Generate a subkey on a card. */
3675 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3676 int keyno, const char *serialno)
3678 int okay=0, rc=0;
3679 KBNODE node;
3680 PKT_secret_key *pri_sk = NULL, *sub_sk;
3681 int algo;
3682 unsigned int use;
3683 u32 expire;
3684 char *passphrase = NULL;
3685 u32 cur_time;
3686 struct para_data_s *para = NULL;
3688 assert (keyno >= 1 && keyno <= 3);
3690 para = xcalloc (1, sizeof *para + strlen (serialno) );
3691 para->key = pSERIALNO;
3692 strcpy (para->u.value, serialno);
3694 /* Break out the primary secret key */
3695 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3696 if (!node)
3698 log_error("Oops; secret key not found anymore!\n");
3699 goto leave;
3702 /* Make a copy of the sk to keep the protected one in the keyblock */
3703 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3705 cur_time = make_timestamp();
3706 if (pri_sk->timestamp > cur_time)
3708 ulong d = pri_sk->timestamp - cur_time;
3709 log_info (d==1 ? _("key has been created %lu second "
3710 "in future (time warp or clock problem)\n")
3711 : _("key has been created %lu seconds "
3712 "in future (time warp or clock problem)\n"), d );
3713 if (!opt.ignore_time_conflict)
3715 rc = G10ERR_TIME_CONFLICT;
3716 goto leave;
3720 if (pri_sk->version < 4)
3722 log_info (_("NOTE: creating subkeys for v3 keys "
3723 "is not OpenPGP compliant\n"));
3724 goto leave;
3727 /* Unprotect to get the passphrase. */
3728 switch( is_secret_key_protected (pri_sk) )
3730 case -1:
3731 rc = G10ERR_PUBKEY_ALGO;
3732 break;
3733 case 0:
3734 tty_printf("This key is not protected.\n");
3735 break;
3736 default:
3737 tty_printf("Key is protected.\n");
3738 rc = check_secret_key( pri_sk, 0 );
3739 if (!rc)
3740 passphrase = get_last_passphrase();
3741 break;
3743 if (rc)
3744 goto leave;
3746 algo = PUBKEY_ALGO_RSA;
3747 expire = ask_expire_interval (0,NULL);
3748 if (keyno == 1)
3749 use = PUBKEY_USAGE_SIG;
3750 else if (keyno == 2)
3751 use = PUBKEY_USAGE_ENC;
3752 else
3753 use = PUBKEY_USAGE_AUTH;
3754 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3755 _("Really create? (y/N) ")))
3756 goto leave;
3758 if (passphrase)
3759 set_next_passphrase (passphrase);
3761 /* Note, that depending on the backend, the card key generation may
3762 update CUR_TIME. */
3763 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3764 &sub_sk, &cur_time, expire, para);
3765 if (!rc)
3766 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3767 use, cur_time);
3768 if (!rc)
3769 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3770 use, cur_time);
3771 if (!rc)
3773 okay = 1;
3774 write_status_text (STATUS_KEY_CREATED, "S");
3777 leave:
3778 if (rc)
3779 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3780 xfree (passphrase);
3781 /* Release the copy of the (now unprotected) secret keys. */
3782 if (pri_sk)
3783 free_secret_key (pri_sk);
3784 set_next_passphrase( NULL );
3785 release_parameter_list (para);
3786 return okay;
3788 #endif /* !ENABLE_CARD_SUPPORT */
3792 * Write a keyblock to an output stream
3794 static int
3795 write_keyblock( IOBUF out, KBNODE node )
3797 for( ; node ; node = node->next )
3799 if(!is_deleted_kbnode(node))
3801 int rc = build_packet( out, node->pkt );
3802 if( rc )
3804 log_error("build_packet(%d) failed: %s\n",
3805 node->pkt->pkttype, g10_errstr(rc) );
3806 return rc;
3811 return 0;
3815 /* Note that timestamp is an in/out arg. */
3816 static int
3817 gen_card_key (int algo, int keyno, int is_primary,
3818 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
3819 u32 *timestamp, u32 expireval, struct para_data_s *para)
3821 #ifdef ENABLE_CARD_SUPPORT
3822 int rc;
3823 const char *s;
3824 struct agent_card_genkey_s info;
3825 PACKET *pkt;
3826 PKT_secret_key *sk;
3827 PKT_public_key *pk;
3829 assert (algo == PUBKEY_ALGO_RSA);
3831 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3832 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
3833 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3834 /* { */
3835 /* tty_printf ("\n"); */
3836 /* log_error ("WARNING: key does already exists!\n"); */
3837 /* tty_printf ("\n"); */
3838 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3839 /* _("Replace existing key? "))) */
3840 /* rc = agent_scd_genkey (&info, keyno, 1); */
3841 /* } */
3843 if (rc)
3845 log_error ("key generation failed: %s\n", gpg_strerror (rc));
3846 return rc;
3848 if ( !info.n || !info.e )
3850 log_error ("communication error with SCD\n");
3851 gcry_mpi_release (info.n);
3852 gcry_mpi_release (info.e);
3853 return gpg_error (GPG_ERR_GENERAL);
3856 if (*timestamp != info.created_at)
3857 log_info ("Note that the key does not use the suggested creation date\n");
3858 *timestamp = info.created_at;
3860 pk = xcalloc (1, sizeof *pk );
3861 sk = xcalloc (1, sizeof *sk );
3862 sk->timestamp = pk->timestamp = info.created_at;
3863 sk->version = pk->version = 4;
3864 if (expireval)
3865 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
3866 sk->pubkey_algo = pk->pubkey_algo = algo;
3867 pk->pkey[0] = info.n;
3868 pk->pkey[1] = info.e;
3869 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
3870 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
3871 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3872 sk->is_protected = 1;
3873 sk->protect.s2k.mode = 1002;
3874 s = get_parameter_value (para, pSERIALNO);
3875 if (s)
3877 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3878 sk->protect.ivlen++, s += 2)
3879 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3882 if( ret_sk )
3883 *ret_sk = sk;
3885 pkt = xcalloc (1,sizeof *pkt);
3886 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
3887 pkt->pkt.public_key = pk;
3888 add_kbnode(pub_root, new_kbnode( pkt ));
3890 pkt = xcalloc (1,sizeof *pkt);
3891 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
3892 pkt->pkt.secret_key = sk;
3893 add_kbnode(sec_root, new_kbnode( pkt ));
3895 return 0;
3896 #else
3897 return -1;
3898 #endif /*!ENABLE_CARD_SUPPORT*/
3903 static int
3904 gen_card_key_with_backup (int algo, int keyno, int is_primary,
3905 KBNODE pub_root, KBNODE sec_root,
3906 u32 timestamp,
3907 u32 expireval, struct para_data_s *para,
3908 const char *backup_dir)
3910 #ifdef ENABLE_CARD_SUPPORT
3911 int rc;
3912 const char *s;
3913 PACKET *pkt;
3914 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
3915 PKT_public_key *pk;
3916 size_t n;
3917 int i;
3919 rc = generate_raw_key (algo, 1024, timestamp,
3920 &sk_unprotected, &sk_protected);
3921 if (rc)
3922 return rc;
3924 /* First, store the key to the card. */
3925 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
3926 if (rc)
3928 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
3929 free_secret_key (sk_unprotected);
3930 free_secret_key (sk_protected);
3931 return rc;
3934 /* Get rid of the secret key parameters and store the serial numer. */
3935 sk = sk_unprotected;
3936 n = pubkey_get_nskey (sk->pubkey_algo);
3937 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
3939 gcry_mpi_release (sk->skey[i]);
3940 sk->skey[i] = NULL;
3942 i = pubkey_get_npkey (sk->pubkey_algo);
3943 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3944 sk->is_protected = 1;
3945 sk->protect.s2k.mode = 1002;
3946 s = get_parameter_value (para, pSERIALNO);
3947 assert (s);
3948 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3949 sk->protect.ivlen++, s += 2)
3950 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3952 /* Now write the *protected* secret key to the file. */
3954 char name_buffer[50];
3955 char *fname;
3956 IOBUF fp;
3957 mode_t oldmask;
3959 keyid_from_sk (sk, NULL);
3960 sprintf (name_buffer,"sk_%08lX%08lX.gpg",
3961 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
3963 fname = make_filename (backup_dir, name_buffer, NULL);
3964 oldmask = umask (077);
3965 if (is_secured_filename (fname))
3967 fp = NULL;
3968 errno = EPERM;
3970 else
3971 fp = iobuf_create (fname);
3972 umask (oldmask);
3973 if (!fp)
3975 rc = gpg_error_from_syserror ();
3976 log_error (_("can't create backup file `%s': %s\n"),
3977 fname, strerror(errno) );
3978 xfree (fname);
3979 free_secret_key (sk_unprotected);
3980 free_secret_key (sk_protected);
3981 return rc;
3984 pkt = xcalloc (1, sizeof *pkt);
3985 pkt->pkttype = PKT_SECRET_KEY;
3986 pkt->pkt.secret_key = sk_protected;
3987 sk_protected = NULL;
3989 rc = build_packet (fp, pkt);
3990 if (rc)
3992 log_error("build packet failed: %s\n", g10_errstr(rc) );
3993 iobuf_cancel (fp);
3995 else
3997 unsigned char array[MAX_FINGERPRINT_LEN];
3998 char *fprbuf, *p;
4000 iobuf_close (fp);
4001 iobuf_ioctl (NULL, 2, 0, (char*)fname);
4002 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
4004 fingerprint_from_sk (sk, array, &n);
4005 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4006 for (i=0; i < n ; i++, p += 2)
4007 sprintf (p, "%02X", array[i]);
4008 *p++ = ' ';
4009 *p = 0;
4011 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4012 fprbuf,
4013 fname, strlen (fname),
4015 xfree (fprbuf);
4017 free_packet (pkt);
4018 xfree (pkt);
4019 xfree (fname);
4020 if (rc)
4022 free_secret_key (sk_unprotected);
4023 return rc;
4027 /* Create the public key from the secret key. */
4028 pk = xcalloc (1, sizeof *pk );
4029 pk->timestamp = sk->timestamp;
4030 pk->version = sk->version;
4031 if (expireval)
4032 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4033 pk->pubkey_algo = sk->pubkey_algo;
4034 n = pubkey_get_npkey (sk->pubkey_algo);
4035 for (i=0; i < n; i++)
4036 pk->pkey[i] = mpi_copy (sk->skey[i]);
4038 /* Build packets and add them to the node lists. */
4039 pkt = xcalloc (1,sizeof *pkt);
4040 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4041 pkt->pkt.public_key = pk;
4042 add_kbnode(pub_root, new_kbnode( pkt ));
4044 pkt = xcalloc (1,sizeof *pkt);
4045 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4046 pkt->pkt.secret_key = sk;
4047 add_kbnode(sec_root, new_kbnode( pkt ));
4049 return 0;
4050 #else
4051 return -1;
4052 #endif /*!ENABLE_CARD_SUPPORT*/
4056 #ifdef ENABLE_CARD_SUPPORT
4058 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
4060 int rc;
4061 unsigned char *rsa_n = NULL;
4062 unsigned char *rsa_e = NULL;
4063 unsigned char *rsa_p = NULL;
4064 unsigned char *rsa_q = NULL;
4065 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4066 unsigned char *sexp = NULL;
4067 unsigned char *p;
4068 char numbuf[55], numbuf2[50];
4070 assert (is_RSA (sk->pubkey_algo));
4071 assert (!sk->is_protected);
4073 /* Copy the parameters into straight buffers. */
4074 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4075 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4076 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4077 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4078 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4080 rc = G10ERR_INV_ARG;
4081 goto leave;
4084 /* Put the key into an S-expression. */
4085 sexp = p = xmalloc_secure (30
4086 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4087 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4089 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4090 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4091 p = stpcpy (p, numbuf);
4092 memcpy (p, rsa_n, rsa_n_len);
4093 p += rsa_n_len;
4095 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4096 p = stpcpy (p, numbuf);
4097 memcpy (p, rsa_e, rsa_e_len);
4098 p += rsa_e_len;
4100 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4101 p = stpcpy (p, numbuf);
4102 memcpy (p, rsa_p, rsa_p_len);
4103 p += rsa_p_len;
4105 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4106 p = stpcpy (p, numbuf);
4107 memcpy (p, rsa_q, rsa_q_len);
4108 p += rsa_q_len;
4110 p = stpcpy (p,"))(10:created-at");
4111 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4112 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4113 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4115 /* Fixme: Unfortunately we don't have the serialnumber available -
4116 thus we can't pass it down to the agent. */
4117 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4119 leave:
4120 xfree (sexp);
4121 xfree (rsa_n);
4122 xfree (rsa_e);
4123 xfree (rsa_p);
4124 xfree (rsa_q);
4125 return rc;
4127 #endif /*ENABLE_CARD_SUPPORT*/