W32 fix
[gnupg.git] / g10 / keygen.c
blobf0de2fbf32bc7ad61a91c3d1230c10cd2f6c9dde
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. Returns -1 on
2291 * error, 0 for no usage given or 1 for usage available.
2293 static int
2294 parse_parameter_usage (const char *fname,
2295 struct para_data_s *para, enum para_name key)
2297 struct para_data_s *r = get_parameter( para, key );
2298 char *p, *pn;
2299 unsigned int use;
2301 if( !r )
2302 return 0; /* none (this is an optional parameter)*/
2304 use = 0;
2305 pn = r->u.value;
2306 while ( (p = strsep (&pn, " \t,")) ) {
2307 if ( !*p)
2309 else if ( !ascii_strcasecmp (p, "sign") )
2310 use |= PUBKEY_USAGE_SIG;
2311 else if ( !ascii_strcasecmp (p, "encrypt") )
2312 use |= PUBKEY_USAGE_ENC;
2313 else if ( !ascii_strcasecmp (p, "auth") )
2314 use |= PUBKEY_USAGE_AUTH;
2315 else {
2316 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2317 return -1; /* error */
2320 r->u.usage = use;
2321 return 1;
2324 static int
2325 parse_revocation_key (const char *fname,
2326 struct para_data_s *para, enum para_name key)
2328 struct para_data_s *r = get_parameter( para, key );
2329 struct revocation_key revkey;
2330 char *pn;
2331 int i;
2333 if( !r )
2334 return 0; /* none (this is an optional parameter) */
2336 pn = r->u.value;
2338 revkey.class=0x80;
2339 revkey.algid=atoi(pn);
2340 if(!revkey.algid)
2341 goto fail;
2343 /* Skip to the fpr */
2344 while(*pn && *pn!=':')
2345 pn++;
2347 if(*pn!=':')
2348 goto fail;
2350 pn++;
2352 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2354 int c=hextobyte(pn);
2355 if(c==-1)
2356 goto fail;
2358 revkey.fpr[i]=c;
2361 /* skip to the tag */
2362 while(*pn && *pn!='s' && *pn!='S')
2363 pn++;
2365 if(ascii_strcasecmp(pn,"sensitive")==0)
2366 revkey.class|=0x40;
2368 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2370 return 0;
2372 fail:
2373 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2374 return -1; /* error */
2378 static u32
2379 get_parameter_u32( struct para_data_s *para, enum para_name key )
2381 struct para_data_s *r = get_parameter( para, key );
2383 if( !r )
2384 return 0;
2385 if( r->key == pKEYCREATIONDATE )
2386 return r->u.creation;
2387 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2388 return r->u.expire;
2389 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2390 return r->u.usage;
2392 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2395 static unsigned int
2396 get_parameter_uint( struct para_data_s *para, enum para_name key )
2398 return get_parameter_u32( para, key );
2401 static DEK *
2402 get_parameter_dek( struct para_data_s *para, enum para_name key )
2404 struct para_data_s *r = get_parameter( para, key );
2405 return r? r->u.dek : NULL;
2408 static STRING2KEY *
2409 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2411 struct para_data_s *r = get_parameter( para, key );
2412 return r? r->u.s2k : NULL;
2415 static struct revocation_key *
2416 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2418 struct para_data_s *r = get_parameter( para, key );
2419 return r? &r->u.revkey : NULL;
2422 static int
2423 proc_parameter_file( struct para_data_s *para, const char *fname,
2424 struct output_control_s *outctrl, int card )
2426 struct para_data_s *r;
2427 const char *s1, *s2, *s3;
2428 size_t n;
2429 char *p;
2430 int have_user_id=0,err,algo;
2432 /* Check that we have all required parameters. */
2433 r = get_parameter( para, pKEYTYPE );
2434 if(r)
2436 algo=get_parameter_algo(para,pKEYTYPE);
2437 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2439 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2440 return -1;
2443 else
2445 log_error ("%s: no Key-Type specified\n",fname);
2446 return -1;
2449 err = parse_parameter_usage (fname, para, pKEYUSAGE);
2450 if (!err)
2452 /* Default to algo capabilities if key-usage is not provided */
2453 r = xmalloc_clear(sizeof(*r));
2454 r->key = pKEYUSAGE;
2455 r->u.usage = openpgp_pk_algo_usage(algo);
2456 r->next = para;
2457 para = r;
2459 else if (err == -1)
2460 return -1;
2461 else
2463 r = get_parameter (para, pKEYUSAGE);
2464 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2466 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2467 fname, r->lnr, algo);
2468 return -1;
2472 r = get_parameter( para, pSUBKEYTYPE );
2473 if(r)
2475 algo = get_parameter_algo (para, pSUBKEYTYPE);
2476 if (openpgp_pk_test_algo (algo))
2478 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2479 return -1;
2482 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2483 if (!err)
2485 /* Default to algo capabilities if subkey-usage is not
2486 provided */
2487 r = xmalloc_clear (sizeof(*r));
2488 r->key = pSUBKEYUSAGE;
2489 r->u.usage = openpgp_pk_algo_usage (algo);
2490 r->next = para;
2491 para = r;
2493 else if (err == -1)
2494 return -1;
2495 else
2497 r = get_parameter (para, pSUBKEYUSAGE);
2498 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2500 log_error ("%s:%d: specified Subkey-Usage not allowed"
2501 " for algo %d\n", fname, r->lnr, algo);
2502 return -1;
2508 if( get_parameter_value( para, pUSERID ) )
2509 have_user_id=1;
2510 else
2512 /* create the formatted user ID */
2513 s1 = get_parameter_value( para, pNAMEREAL );
2514 s2 = get_parameter_value( para, pNAMECOMMENT );
2515 s3 = get_parameter_value( para, pNAMEEMAIL );
2516 if( s1 || s2 || s3 )
2518 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2519 r = xmalloc_clear( sizeof *r + n + 20 );
2520 r->key = pUSERID;
2521 p = r->u.value;
2522 if( s1 )
2523 p = stpcpy(p, s1 );
2524 if( s2 )
2525 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2526 if( s3 )
2527 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2528 r->next = para;
2529 para = r;
2530 have_user_id=1;
2534 if(!have_user_id)
2536 log_error("%s: no User-ID specified\n",fname);
2537 return -1;
2540 /* Set preferences, if any. */
2541 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2543 /* Set keyserver, if any. */
2544 s1=get_parameter_value( para, pKEYSERVER );
2545 if(s1)
2547 struct keyserver_spec *spec;
2549 spec=parse_keyserver_uri(s1,1,NULL,0);
2550 if(spec)
2552 free_keyserver_spec(spec);
2553 opt.def_keyserver_url=s1;
2555 else
2557 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2558 return -1;
2562 /* Set revoker, if any. */
2563 if (parse_revocation_key (fname, para, pREVOKER))
2564 return -1;
2566 /* Make DEK and S2K from the Passphrase. */
2567 if (outctrl->ask_passphrase)
2569 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2570 feature is required so that GUIs are able to do a key
2571 creation but have gpg-agent ask for the passphrase. */
2572 int canceled = 0;
2573 STRING2KEY *s2k;
2574 DEK *dek;
2576 dek = do_ask_passphrase ( &s2k, &canceled );
2577 if (dek)
2579 r = xmalloc_clear( sizeof *r );
2580 r->key = pPASSPHRASE_DEK;
2581 r->u.dek = dek;
2582 r->next = para;
2583 para = r;
2584 r = xmalloc_clear( sizeof *r );
2585 r->key = pPASSPHRASE_S2K;
2586 r->u.s2k = s2k;
2587 r->next = para;
2588 para = r;
2591 if (canceled)
2593 log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
2594 return -1;
2597 else
2599 r = get_parameter( para, pPASSPHRASE );
2600 if ( r && *r->u.value )
2602 /* We have a plain text passphrase - create a DEK from it.
2603 * It is a little bit ridiculous to keep it in secure memory
2604 * but because we do this always, why not here. */
2605 STRING2KEY *s2k;
2606 DEK *dek;
2608 s2k = xmalloc_secure ( sizeof *s2k );
2609 s2k->mode = opt.s2k_mode;
2610 s2k->hash_algo = S2K_DIGEST_ALGO;
2611 set_next_passphrase ( r->u.value );
2612 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2613 NULL, NULL);
2614 set_next_passphrase (NULL );
2615 assert (dek);
2616 memset (r->u.value, 0, strlen(r->u.value));
2618 r = xmalloc_clear (sizeof *r);
2619 r->key = pPASSPHRASE_S2K;
2620 r->u.s2k = s2k;
2621 r->next = para;
2622 para = r;
2623 r = xmalloc_clear (sizeof *r);
2624 r->key = pPASSPHRASE_DEK;
2625 r->u.dek = dek;
2626 r->next = para;
2627 para = r;
2631 /* Make KEYCREATIONDATE from Creation-Date. */
2632 r = get_parameter (para, pCREATIONDATE);
2633 if (r && *r->u.value)
2635 u32 seconds;
2637 seconds = parse_creation_string (r->u.value);
2638 if (!seconds)
2640 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2641 return -1;
2643 r->u.creation = seconds;
2644 r->key = pKEYCREATIONDATE; /* Change that entry. */
2647 /* Make KEYEXPIRE from Expire-Date. */
2648 r = get_parameter( para, pEXPIREDATE );
2649 if( r && *r->u.value )
2651 u32 seconds;
2653 seconds = parse_expire_string( r->u.value );
2654 if( seconds == (u32)-1 )
2656 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2657 return -1;
2659 r->u.expire = seconds;
2660 r->key = pKEYEXPIRE; /* change hat entry */
2661 /* also set it for the subkey */
2662 r = xmalloc_clear( sizeof *r + 20 );
2663 r->key = pSUBKEYEXPIRE;
2664 r->u.expire = seconds;
2665 r->next = para;
2666 para = r;
2669 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2670 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2671 return -1;
2674 do_generate_keypair( para, outctrl, card );
2675 return 0;
2679 /****************
2680 * Kludge to allow non interactive key generation controlled
2681 * by a parameter file.
2682 * Note, that string parameters are expected to be in UTF-8
2684 static void
2685 read_parameter_file( const char *fname )
2687 static struct { const char *name;
2688 enum para_name key;
2689 } keywords[] = {
2690 { "Key-Type", pKEYTYPE},
2691 { "Key-Length", pKEYLENGTH },
2692 { "Key-Usage", pKEYUSAGE },
2693 { "Subkey-Type", pSUBKEYTYPE },
2694 { "Subkey-Length", pSUBKEYLENGTH },
2695 { "Subkey-Usage", pSUBKEYUSAGE },
2696 { "Name-Real", pNAMEREAL },
2697 { "Name-Email", pNAMEEMAIL },
2698 { "Name-Comment", pNAMECOMMENT },
2699 { "Expire-Date", pEXPIREDATE },
2700 { "Creation-Date", pCREATIONDATE },
2701 { "Passphrase", pPASSPHRASE },
2702 { "Preferences", pPREFERENCES },
2703 { "Revoker", pREVOKER },
2704 { "Handle", pHANDLE },
2705 { "Keyserver", pKEYSERVER },
2706 { NULL, 0 }
2708 IOBUF fp;
2709 byte *line;
2710 unsigned int maxlen, nline;
2711 char *p;
2712 int lnr;
2713 const char *err = NULL;
2714 struct para_data_s *para, *r;
2715 int i;
2716 struct output_control_s outctrl;
2718 memset( &outctrl, 0, sizeof( outctrl ) );
2719 outctrl.pub.afx = new_armor_context ();
2720 outctrl.sec.afx = new_armor_context ();
2722 if( !fname || !*fname)
2723 fname = "-";
2725 fp = iobuf_open (fname);
2726 if (fp && is_secured_file (iobuf_get_fd (fp)))
2728 iobuf_close (fp);
2729 fp = NULL;
2730 errno = EPERM;
2732 if (!fp) {
2733 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2734 return;
2736 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2738 lnr = 0;
2739 err = NULL;
2740 para = NULL;
2741 maxlen = 1024;
2742 line = NULL;
2743 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2744 char *keyword, *value;
2746 lnr++;
2747 if( !maxlen ) {
2748 err = "line too long";
2749 break;
2751 for( p = line; isspace(*(byte*)p); p++ )
2753 if( !*p || *p == '#' )
2754 continue;
2755 keyword = p;
2756 if( *keyword == '%' ) {
2757 for( ; !isspace(*(byte*)p); p++ )
2759 if( *p )
2760 *p++ = 0;
2761 for( ; isspace(*(byte*)p); p++ )
2763 value = p;
2764 trim_trailing_ws( value, strlen(value) );
2765 if( !ascii_strcasecmp( keyword, "%echo" ) )
2766 log_info("%s\n", value );
2767 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2768 outctrl.dryrun = 1;
2769 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
2770 outctrl.ask_passphrase = 1;
2771 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
2772 outctrl.ask_passphrase = 0;
2773 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2774 outctrl.lnr = lnr;
2775 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2776 print_status_key_not_created
2777 (get_parameter_value (para, pHANDLE));
2778 release_parameter_list( para );
2779 para = NULL;
2781 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2782 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2783 ; /* still the same file - ignore it */
2784 else {
2785 xfree( outctrl.pub.newfname );
2786 outctrl.pub.newfname = xstrdup( value );
2787 outctrl.use_files = 1;
2790 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2791 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2792 ; /* still the same file - ignore it */
2793 else {
2794 xfree( outctrl.sec.newfname );
2795 outctrl.sec.newfname = xstrdup( value );
2796 outctrl.use_files = 1;
2799 else
2800 log_info("skipping control `%s' (%s)\n", keyword, value );
2803 continue;
2807 if( !(p = strchr( p, ':' )) || p == keyword ) {
2808 err = "missing colon";
2809 break;
2811 if( *p )
2812 *p++ = 0;
2813 for( ; isspace(*(byte*)p); p++ )
2815 if( !*p ) {
2816 err = "missing argument";
2817 break;
2819 value = p;
2820 trim_trailing_ws( value, strlen(value) );
2822 for(i=0; keywords[i].name; i++ ) {
2823 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2824 break;
2826 if( !keywords[i].name ) {
2827 err = "unknown keyword";
2828 break;
2830 if( keywords[i].key != pKEYTYPE && !para ) {
2831 err = "parameter block does not start with \"Key-Type\"";
2832 break;
2835 if( keywords[i].key == pKEYTYPE && para ) {
2836 outctrl.lnr = lnr;
2837 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2838 print_status_key_not_created
2839 (get_parameter_value (para, pHANDLE));
2840 release_parameter_list( para );
2841 para = NULL;
2843 else {
2844 for( r = para; r; r = r->next ) {
2845 if( r->key == keywords[i].key )
2846 break;
2848 if( r ) {
2849 err = "duplicate keyword";
2850 break;
2853 r = xmalloc_clear( sizeof *r + strlen( value ) );
2854 r->lnr = lnr;
2855 r->key = keywords[i].key;
2856 strcpy( r->u.value, value );
2857 r->next = para;
2858 para = r;
2860 if( err )
2861 log_error("%s:%d: %s\n", fname, lnr, err );
2862 else if( iobuf_error (fp) ) {
2863 log_error("%s:%d: read error\n", fname, lnr);
2865 else if( para ) {
2866 outctrl.lnr = lnr;
2867 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2868 print_status_key_not_created (get_parameter_value (para, pHANDLE));
2871 if( outctrl.use_files ) { /* close open streams */
2872 iobuf_close( outctrl.pub.stream );
2873 iobuf_close( outctrl.sec.stream );
2875 /* Must invalidate that ugly cache to actually close it. */
2876 if (outctrl.pub.fname)
2877 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
2878 if (outctrl.sec.fname)
2879 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
2881 xfree( outctrl.pub.fname );
2882 xfree( outctrl.pub.newfname );
2883 xfree( outctrl.sec.fname );
2884 xfree( outctrl.sec.newfname );
2887 release_parameter_list( para );
2888 iobuf_close (fp);
2889 release_armor_context (outctrl.pub.afx);
2890 release_armor_context (outctrl.sec.afx);
2895 * Generate a keypair (fname is only used in batch mode) If
2896 * CARD_SERIALNO is not NULL the function will create the keys on an
2897 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2898 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2899 * generate in software, imported to the card and a backup file
2900 * written to directory given by this argument .
2902 void
2903 generate_keypair (const char *fname, const char *card_serialno,
2904 const char *backup_encryption_dir)
2906 unsigned int nbits;
2907 char *uid = NULL;
2908 DEK *dek;
2909 STRING2KEY *s2k;
2910 int algo;
2911 unsigned int use;
2912 int both = 0;
2913 u32 expire;
2914 struct para_data_s *para = NULL;
2915 struct para_data_s *r;
2916 struct output_control_s outctrl;
2917 int canceled;
2919 memset( &outctrl, 0, sizeof( outctrl ) );
2921 if (opt.batch && card_serialno)
2923 /* We don't yet support unattended key generation. */
2924 log_error (_("can't do this in batch mode\n"));
2925 return;
2928 if (opt.batch)
2930 read_parameter_file( fname );
2931 return;
2934 if (card_serialno)
2936 #ifdef ENABLE_CARD_SUPPORT
2937 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
2938 r->key = pSERIALNO;
2939 strcpy( r->u.value, card_serialno);
2940 r->next = para;
2941 para = r;
2943 algo = PUBKEY_ALGO_RSA;
2945 r = xcalloc (1, sizeof *r + 20 );
2946 r->key = pKEYTYPE;
2947 sprintf( r->u.value, "%d", algo );
2948 r->next = para;
2949 para = r;
2950 r = xcalloc (1, sizeof *r + 20 );
2951 r->key = pKEYUSAGE;
2952 strcpy (r->u.value, "sign");
2953 r->next = para;
2954 para = r;
2956 r = xcalloc (1, sizeof *r + 20 );
2957 r->key = pSUBKEYTYPE;
2958 sprintf( r->u.value, "%d", algo );
2959 r->next = para;
2960 para = r;
2961 r = xcalloc (1, sizeof *r + 20 );
2962 r->key = pSUBKEYUSAGE;
2963 strcpy (r->u.value, "encrypt");
2964 r->next = para;
2965 para = r;
2967 r = xcalloc (1, sizeof *r + 20 );
2968 r->key = pAUTHKEYTYPE;
2969 sprintf( r->u.value, "%d", algo );
2970 r->next = para;
2971 para = r;
2973 if (backup_encryption_dir)
2975 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
2976 r->key = pBACKUPENCDIR;
2977 strcpy (r->u.value, backup_encryption_dir);
2978 r->next = para;
2979 para = r;
2981 #endif /*ENABLE_CARD_SUPPORT*/
2983 else
2985 algo = ask_algo( 0, &use );
2986 if( !algo )
2987 { /* default: DSA with ElG subkey of the specified size */
2988 both = 1;
2989 r = xmalloc_clear( sizeof *r + 20 );
2990 r->key = pKEYTYPE;
2991 sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
2992 r->next = para;
2993 para = r;
2994 nbits = ask_keysize( PUBKEY_ALGO_DSA );
2995 r = xmalloc_clear( sizeof *r + 20 );
2996 r->key = pKEYLENGTH;
2997 sprintf( r->u.value, "%u", nbits);
2998 r->next = para;
2999 para = r;
3000 r = xmalloc_clear( sizeof *r + 20 );
3001 r->key = pKEYUSAGE;
3002 strcpy( r->u.value, "sign" );
3003 r->next = para;
3004 para = r;
3006 algo = PUBKEY_ALGO_ELGAMAL_E;
3007 r = xmalloc_clear( sizeof *r + 20 );
3008 r->key = pSUBKEYTYPE;
3009 sprintf( r->u.value, "%d", algo );
3010 r->next = para;
3011 para = r;
3012 r = xmalloc_clear( sizeof *r + 20 );
3013 r->key = pSUBKEYUSAGE;
3014 strcpy( r->u.value, "encrypt" );
3015 r->next = para;
3016 para = r;
3018 else
3020 r = xmalloc_clear( sizeof *r + 20 );
3021 r->key = pKEYTYPE;
3022 sprintf( r->u.value, "%d", algo );
3023 r->next = para;
3024 para = r;
3026 if (use)
3028 r = xmalloc_clear( sizeof *r + 25 );
3029 r->key = pKEYUSAGE;
3030 sprintf( r->u.value, "%s%s%s",
3031 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3032 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3033 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3034 r->next = para;
3035 para = r;
3040 nbits = ask_keysize( algo );
3041 r = xmalloc_clear( sizeof *r + 20 );
3042 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3043 sprintf( r->u.value, "%u", nbits);
3044 r->next = para;
3045 para = r;
3048 expire = ask_expire_interval(0,NULL);
3049 r = xmalloc_clear( sizeof *r + 20 );
3050 r->key = pKEYEXPIRE;
3051 r->u.expire = expire;
3052 r->next = para;
3053 para = r;
3054 r = xmalloc_clear( sizeof *r + 20 );
3055 r->key = pSUBKEYEXPIRE;
3056 r->u.expire = expire;
3057 r->next = para;
3058 para = r;
3060 uid = ask_user_id(0);
3061 if( !uid )
3063 log_error(_("Key generation canceled.\n"));
3064 release_parameter_list( para );
3065 return;
3067 r = xmalloc_clear( sizeof *r + strlen(uid) );
3068 r->key = pUSERID;
3069 strcpy( r->u.value, uid );
3070 r->next = para;
3071 para = r;
3073 canceled = 0;
3074 dek = card_serialno? NULL : do_ask_passphrase ( &s2k, &canceled );
3075 if( dek )
3077 r = xmalloc_clear( sizeof *r );
3078 r->key = pPASSPHRASE_DEK;
3079 r->u.dek = dek;
3080 r->next = para;
3081 para = r;
3082 r = xmalloc_clear( sizeof *r );
3083 r->key = pPASSPHRASE_S2K;
3084 r->u.s2k = s2k;
3085 r->next = para;
3086 para = r;
3089 if (canceled)
3090 log_error (_("Key generation canceled.\n"));
3091 else
3092 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3093 release_parameter_list( para );
3097 #ifdef ENABLE_CARD_SUPPORT
3098 /* Generate a raw key and return it as a secret key packet. The
3099 function will ask for the passphrase and return a protected as well
3100 as an unprotected copy of a new secret key packet. 0 is returned
3101 on success and the caller must then free the returned values. */
3102 static int
3103 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3104 PKT_secret_key **r_sk_unprotected,
3105 PKT_secret_key **r_sk_protected)
3107 int rc;
3108 DEK *dek = NULL;
3109 STRING2KEY *s2k = NULL;
3110 PKT_secret_key *sk = NULL;
3111 int i;
3112 size_t nskey, npkey;
3113 gcry_sexp_t s_parms, s_key;
3114 int canceled;
3116 npkey = pubkey_get_npkey (algo);
3117 nskey = pubkey_get_nskey (algo);
3118 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3120 if (nbits < 512)
3122 nbits = 512;
3123 log_info (_("keysize invalid; using %u bits\n"), nbits );
3126 if ((nbits % 32))
3128 nbits = ((nbits + 31) / 32) * 32;
3129 log_info(_("keysize rounded up to %u bits\n"), nbits );
3132 dek = do_ask_passphrase (&s2k, &canceled);
3133 if (canceled)
3135 rc = gpg_error (GPG_ERR_CANCELED);
3136 goto leave;
3139 sk = xmalloc_clear (sizeof *sk);
3140 sk->timestamp = created_at;
3141 sk->version = 4;
3142 sk->pubkey_algo = algo;
3144 if ( !is_RSA (algo) )
3146 log_error ("only RSA is supported for offline generated keys\n");
3147 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3148 goto leave;
3150 rc = gcry_sexp_build (&s_parms, NULL,
3151 "(genkey(rsa(nbits %d)))",
3152 (int)nbits);
3153 if (rc)
3154 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3155 rc = gcry_pk_genkey (&s_key, s_parms);
3156 gcry_sexp_release (s_parms);
3157 if (rc)
3159 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3160 goto leave;
3162 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3163 gcry_sexp_release (s_key);
3164 if (rc)
3166 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3167 goto leave;
3170 for (i=npkey; i < nskey; i++)
3171 sk->csum += checksum_mpi (sk->skey[i]);
3173 if (r_sk_unprotected)
3174 *r_sk_unprotected = copy_secret_key (NULL, sk);
3176 rc = genhelp_protect (dek, s2k, sk);
3177 if (rc)
3178 goto leave;
3180 if (r_sk_protected)
3182 *r_sk_protected = sk;
3183 sk = NULL;
3186 leave:
3187 if (sk)
3188 free_secret_key (sk);
3189 xfree (dek);
3190 xfree (s2k);
3191 return rc;
3193 #endif /* ENABLE_CARD_SUPPORT */
3195 /* Create and delete a dummy packet to start off a list of kbnodes. */
3196 static void
3197 start_tree(KBNODE *tree)
3199 PACKET *pkt;
3201 pkt=xmalloc_clear(sizeof(*pkt));
3202 pkt->pkttype=PKT_NONE;
3203 *tree=new_kbnode(pkt);
3204 delete_kbnode(*tree);
3208 static void
3209 do_generate_keypair (struct para_data_s *para,
3210 struct output_control_s *outctrl, int card)
3212 KBNODE pub_root = NULL;
3213 KBNODE sec_root = NULL;
3214 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3215 const char *s;
3216 struct revocation_key *revkey;
3217 int rc;
3218 int did_sub = 0;
3219 u32 timestamp;
3221 if( outctrl->dryrun )
3223 log_info("dry-run mode - key generation skipped\n");
3224 return;
3227 if ( outctrl->use_files )
3229 if ( outctrl->pub.newfname )
3231 iobuf_close(outctrl->pub.stream);
3232 outctrl->pub.stream = NULL;
3233 if (outctrl->pub.fname)
3234 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3235 xfree( outctrl->pub.fname );
3236 outctrl->pub.fname = outctrl->pub.newfname;
3237 outctrl->pub.newfname = NULL;
3239 if (is_secured_filename (outctrl->pub.fname) )
3241 outctrl->pub.stream = NULL;
3242 errno = EPERM;
3244 else
3245 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3246 if (!outctrl->pub.stream)
3248 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3249 strerror(errno) );
3250 return;
3252 if (opt.armor)
3254 outctrl->pub.afx->what = 1;
3255 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3258 if (outctrl->sec.newfname)
3260 mode_t oldmask;
3262 iobuf_close(outctrl->sec.stream);
3263 outctrl->sec.stream = NULL;
3264 if (outctrl->sec.fname)
3265 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3266 xfree( outctrl->sec.fname );
3267 outctrl->sec.fname = outctrl->sec.newfname;
3268 outctrl->sec.newfname = NULL;
3270 oldmask = umask (077);
3271 if (is_secured_filename (outctrl->sec.fname) )
3273 outctrl->sec.stream = NULL;
3274 errno = EPERM;
3276 else
3277 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3278 umask (oldmask);
3279 if (!outctrl->sec.stream)
3281 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3282 strerror(errno) );
3283 return;
3285 if (opt.armor)
3287 outctrl->sec.afx->what = 5;
3288 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3291 assert( outctrl->pub.stream );
3292 assert( outctrl->sec.stream );
3293 if (opt.verbose)
3295 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3296 if (card)
3297 log_info (_("writing secret key stub to `%s'\n"),
3298 outctrl->sec.fname);
3299 else
3300 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3305 /* We create the packets as a tree of kbnodes. Because the
3306 structure we create is known in advance we simply generate a
3307 linked list. The first packet is a dummy packet which we flag as
3308 deleted. The very first packet must always be a KEY packet. */
3310 start_tree (&pub_root);
3311 start_tree (&sec_root);
3313 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3314 if (!timestamp)
3315 timestamp = make_timestamp ();
3317 if (!card)
3319 rc = do_create (get_parameter_algo( para, pKEYTYPE ),
3320 get_parameter_uint( para, pKEYLENGTH ),
3321 pub_root, sec_root,
3322 get_parameter_dek( para, pPASSPHRASE_DEK ),
3323 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3324 &pri_sk,
3325 timestamp,
3326 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3328 else
3330 /* Note, that depending on the backend, the card key generation
3331 may update TIMESTAMP. */
3332 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3333 &timestamp,
3334 get_parameter_u32 (para, pKEYEXPIRE), para);
3335 if (!rc)
3337 pri_sk = sec_root->next->pkt->pkt.secret_key;
3338 assert (pri_sk);
3342 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3344 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3345 if (!rc)
3346 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3349 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3351 write_uid (pub_root, s );
3352 write_uid (sec_root, s );
3354 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3355 get_parameter_uint (para, pKEYUSAGE), timestamp);
3358 /* Write the auth key to the card before the encryption key. This
3359 is a partial workaround for a PGP bug (as of this writing, all
3360 versions including 8.1), that causes it to try and encrypt to
3361 the most recent subkey regardless of whether that subkey is
3362 actually an encryption type. In this case, the auth key is an
3363 RSA key so it succeeds. */
3365 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3367 /* Note, that depending on the backend, the card key generation
3368 may update TIMESTAMP. */
3369 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3370 &timestamp,
3371 get_parameter_u32 (para, pKEYEXPIRE), para);
3373 if (!rc)
3374 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3375 PUBKEY_USAGE_AUTH, timestamp);
3376 if (!rc)
3377 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3378 PUBKEY_USAGE_AUTH, timestamp);
3381 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3383 if (!card)
3385 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
3386 get_parameter_uint( para, pSUBKEYLENGTH ),
3387 pub_root, sec_root,
3388 get_parameter_dek( para, pPASSPHRASE_DEK ),
3389 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3390 &sub_sk,
3391 timestamp,
3392 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3394 else
3396 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3398 /* A backup of the encryption key has been requested.
3399 Generate the key in software and import it then to
3400 the card. Write a backup file. */
3401 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3402 pub_root, sec_root,
3403 timestamp,
3404 get_parameter_u32 (para,
3405 pKEYEXPIRE),
3406 para, s);
3408 else
3410 /* Note, that depending on the backend, the card key
3411 generation may update TIMESTAMP. */
3412 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3413 NULL,
3414 &timestamp,
3415 get_parameter_u32 (para, pKEYEXPIRE), para);
3419 if( !rc )
3420 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3421 get_parameter_uint (para, pSUBKEYUSAGE),
3422 timestamp);
3423 if( !rc )
3424 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3425 get_parameter_uint (para, pSUBKEYUSAGE),
3426 timestamp);
3427 did_sub = 1;
3430 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3432 rc = write_keyblock( outctrl->pub.stream, pub_root );
3433 if (rc)
3434 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3435 if (!rc)
3437 rc = write_keyblock( outctrl->sec.stream, sec_root );
3438 if(rc)
3439 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3442 else if (!rc) /* Write to the standard keyrings. */
3444 KEYDB_HANDLE pub_hd = keydb_new (0);
3445 KEYDB_HANDLE sec_hd = keydb_new (1);
3447 rc = keydb_locate_writable (pub_hd, NULL);
3448 if (rc)
3449 log_error (_("no writable public keyring found: %s\n"),
3450 g10_errstr (rc));
3452 if (!rc)
3454 rc = keydb_locate_writable (sec_hd, NULL);
3455 if (rc)
3456 log_error (_("no writable secret keyring found: %s\n"),
3457 g10_errstr (rc));
3460 if (!rc && opt.verbose)
3462 log_info (_("writing public key to `%s'\n"),
3463 keydb_get_resource_name (pub_hd));
3464 if (card)
3465 log_info (_("writing secret key stub to `%s'\n"),
3466 keydb_get_resource_name (sec_hd));
3467 else
3468 log_info (_("writing secret key to `%s'\n"),
3469 keydb_get_resource_name (sec_hd));
3472 if (!rc)
3474 rc = keydb_insert_keyblock (pub_hd, pub_root);
3475 if (rc)
3476 log_error (_("error writing public keyring `%s': %s\n"),
3477 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3480 if (!rc)
3482 rc = keydb_insert_keyblock (sec_hd, sec_root);
3483 if (rc)
3484 log_error (_("error writing secret keyring `%s': %s\n"),
3485 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3488 keydb_release (pub_hd);
3489 keydb_release (sec_hd);
3491 if (!rc)
3493 int no_enc_rsa;
3494 PKT_public_key *pk;
3496 no_enc_rsa = (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
3497 && get_parameter_uint (para, pKEYUSAGE)
3498 && !((get_parameter_uint (para, pKEYUSAGE)
3499 & PUBKEY_USAGE_ENC)) );
3501 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3503 keyid_from_pk(pk,pk->main_keyid);
3504 register_trusted_keyid(pk->main_keyid);
3506 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3507 | TRUST_ULTIMATE ));
3509 if (!opt.batch)
3511 tty_printf (_("public and secret key created and signed.\n") );
3512 tty_printf ("\n");
3513 list_keyblock(pub_root,0,1,NULL);
3517 if (!opt.batch
3518 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
3519 || no_enc_rsa )
3520 && !get_parameter (para, pSUBKEYTYPE) )
3522 tty_printf(_("Note that this key cannot be used for "
3523 "encryption. You may want to use\n"
3524 "the command \"--edit-key\" to generate a "
3525 "subkey for this purpose.\n") );
3530 if (rc)
3532 if (opt.batch)
3533 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3534 else
3535 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3536 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3538 else
3540 PKT_public_key *pk = find_kbnode (pub_root,
3541 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3542 print_status_key_created (did_sub? 'B':'P', pk,
3543 get_parameter_value (para, pHANDLE));
3545 release_kbnode( pub_root );
3546 release_kbnode( sec_root );
3548 if (pri_sk && !card) /* The unprotected secret key unless we */
3549 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3550 if (sub_sk)
3551 free_secret_key(sub_sk);
3555 /* Add a new subkey to an existing key. Returns true if a new key has
3556 been generated and put into the keyblocks. */
3558 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3560 int okay=0, rc=0;
3561 KBNODE node;
3562 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3563 int algo;
3564 unsigned int use;
3565 u32 expire;
3566 unsigned nbits;
3567 char *passphrase = NULL;
3568 DEK *dek = NULL;
3569 STRING2KEY *s2k = NULL;
3570 u32 cur_time;
3571 int ask_pass = 0;
3572 int canceled;
3574 /* Break out the primary secret key. */
3575 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3576 if( !node )
3578 log_error ("Oops; secret key not found anymore!\n");
3579 goto leave;
3582 /* Make a copy of the sk to keep the protected one in the keyblock. */
3583 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3585 cur_time = make_timestamp();
3587 if (pri_sk->timestamp > cur_time)
3589 ulong d = pri_sk->timestamp - cur_time;
3590 log_info ( d==1 ? _("key has been created %lu second "
3591 "in future (time warp or clock problem)\n")
3592 : _("key has been created %lu seconds "
3593 "in future (time warp or clock problem)\n"), d );
3594 if (!opt.ignore_time_conflict)
3596 rc = G10ERR_TIME_CONFLICT;
3597 goto leave;
3601 if (pri_sk->version < 4)
3603 log_info (_("NOTE: creating subkeys for v3 keys "
3604 "is not OpenPGP compliant\n"));
3605 goto leave;
3608 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3610 tty_printf (_("Secret parts of primary key are not available.\n"));
3611 rc = G10ERR_NO_SECKEY;
3612 goto leave;
3616 /* Unprotect to get the passphrase. */
3617 switch (is_secret_key_protected (pri_sk) )
3619 case -1:
3620 rc = G10ERR_PUBKEY_ALGO;
3621 break;
3622 case 0:
3623 tty_printf (_("This key is not protected.\n"));
3624 break;
3625 case -2:
3626 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3627 ask_pass = 1;
3628 break;
3629 default:
3630 tty_printf (_("Key is protected.\n"));
3631 rc = check_secret_key ( pri_sk, 0 );
3632 if (!rc)
3633 passphrase = get_last_passphrase();
3634 break;
3636 if (rc)
3637 goto leave;
3639 algo = ask_algo (1, &use);
3640 assert (algo);
3641 nbits = ask_keysize (algo);
3642 expire = ask_expire_interval (0, NULL);
3643 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3644 _("Really create? (y/N) ")))
3645 goto leave;
3647 canceled = 0;
3648 if (ask_pass)
3649 dek = do_ask_passphrase (&s2k, &canceled);
3650 else if (passphrase)
3652 s2k = xmalloc_secure ( sizeof *s2k );
3653 s2k->mode = opt.s2k_mode;
3654 s2k->hash_algo = S2K_DIGEST_ALGO;
3655 set_next_passphrase ( passphrase );
3656 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3657 NULL, NULL );
3660 if (canceled)
3661 rc = GPG_ERR_CANCELED;
3663 if (!rc)
3664 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3665 dek, s2k, &sub_sk, cur_time, expire, 1 );
3666 if (!rc)
3667 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3668 use, cur_time);
3669 if (!rc)
3670 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3671 use, cur_time);
3672 if (!rc)
3674 okay = 1;
3675 write_status_text (STATUS_KEY_CREATED, "S");
3678 leave:
3679 if (rc)
3680 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3681 xfree (passphrase);
3682 xfree (dek);
3683 xfree (s2k);
3684 /* Release the copy of the (now unprotected) secret keys. */
3685 if (pri_sk)
3686 free_secret_key (pri_sk);
3687 if (sub_sk)
3688 free_secret_key (sub_sk);
3689 set_next_passphrase (NULL);
3690 return okay;
3694 #ifdef ENABLE_CARD_SUPPORT
3695 /* Generate a subkey on a card. */
3697 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3698 int keyno, const char *serialno)
3700 int okay=0, rc=0;
3701 KBNODE node;
3702 PKT_secret_key *pri_sk = NULL, *sub_sk;
3703 int algo;
3704 unsigned int use;
3705 u32 expire;
3706 char *passphrase = NULL;
3707 u32 cur_time;
3708 struct para_data_s *para = NULL;
3710 assert (keyno >= 1 && keyno <= 3);
3712 para = xcalloc (1, sizeof *para + strlen (serialno) );
3713 para->key = pSERIALNO;
3714 strcpy (para->u.value, serialno);
3716 /* Break out the primary secret key */
3717 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3718 if (!node)
3720 log_error("Oops; secret key not found anymore!\n");
3721 goto leave;
3724 /* Make a copy of the sk to keep the protected one in the keyblock */
3725 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3727 cur_time = make_timestamp();
3728 if (pri_sk->timestamp > cur_time)
3730 ulong d = pri_sk->timestamp - cur_time;
3731 log_info (d==1 ? _("key has been created %lu second "
3732 "in future (time warp or clock problem)\n")
3733 : _("key has been created %lu seconds "
3734 "in future (time warp or clock problem)\n"), d );
3735 if (!opt.ignore_time_conflict)
3737 rc = G10ERR_TIME_CONFLICT;
3738 goto leave;
3742 if (pri_sk->version < 4)
3744 log_info (_("NOTE: creating subkeys for v3 keys "
3745 "is not OpenPGP compliant\n"));
3746 goto leave;
3749 /* Unprotect to get the passphrase. */
3750 switch( is_secret_key_protected (pri_sk) )
3752 case -1:
3753 rc = G10ERR_PUBKEY_ALGO;
3754 break;
3755 case 0:
3756 tty_printf("This key is not protected.\n");
3757 break;
3758 default:
3759 tty_printf("Key is protected.\n");
3760 rc = check_secret_key( pri_sk, 0 );
3761 if (!rc)
3762 passphrase = get_last_passphrase();
3763 break;
3765 if (rc)
3766 goto leave;
3768 algo = PUBKEY_ALGO_RSA;
3769 expire = ask_expire_interval (0,NULL);
3770 if (keyno == 1)
3771 use = PUBKEY_USAGE_SIG;
3772 else if (keyno == 2)
3773 use = PUBKEY_USAGE_ENC;
3774 else
3775 use = PUBKEY_USAGE_AUTH;
3776 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3777 _("Really create? (y/N) ")))
3778 goto leave;
3780 if (passphrase)
3781 set_next_passphrase (passphrase);
3783 /* Note, that depending on the backend, the card key generation may
3784 update CUR_TIME. */
3785 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3786 &sub_sk, &cur_time, expire, para);
3787 if (!rc)
3788 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3789 use, cur_time);
3790 if (!rc)
3791 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3792 use, cur_time);
3793 if (!rc)
3795 okay = 1;
3796 write_status_text (STATUS_KEY_CREATED, "S");
3799 leave:
3800 if (rc)
3801 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3802 xfree (passphrase);
3803 /* Release the copy of the (now unprotected) secret keys. */
3804 if (pri_sk)
3805 free_secret_key (pri_sk);
3806 set_next_passphrase( NULL );
3807 release_parameter_list (para);
3808 return okay;
3810 #endif /* !ENABLE_CARD_SUPPORT */
3814 * Write a keyblock to an output stream
3816 static int
3817 write_keyblock( IOBUF out, KBNODE node )
3819 for( ; node ; node = node->next )
3821 if(!is_deleted_kbnode(node))
3823 int rc = build_packet( out, node->pkt );
3824 if( rc )
3826 log_error("build_packet(%d) failed: %s\n",
3827 node->pkt->pkttype, g10_errstr(rc) );
3828 return rc;
3833 return 0;
3837 /* Note that timestamp is an in/out arg. */
3838 static int
3839 gen_card_key (int algo, int keyno, int is_primary,
3840 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
3841 u32 *timestamp, u32 expireval, struct para_data_s *para)
3843 #ifdef ENABLE_CARD_SUPPORT
3844 int rc;
3845 const char *s;
3846 struct agent_card_genkey_s info;
3847 PACKET *pkt;
3848 PKT_secret_key *sk;
3849 PKT_public_key *pk;
3851 assert (algo == PUBKEY_ALGO_RSA);
3853 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3854 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
3855 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3856 /* { */
3857 /* tty_printf ("\n"); */
3858 /* log_error ("WARNING: key does already exists!\n"); */
3859 /* tty_printf ("\n"); */
3860 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3861 /* _("Replace existing key? "))) */
3862 /* rc = agent_scd_genkey (&info, keyno, 1); */
3863 /* } */
3865 if (rc)
3867 log_error ("key generation failed: %s\n", gpg_strerror (rc));
3868 return rc;
3870 if ( !info.n || !info.e )
3872 log_error ("communication error with SCD\n");
3873 gcry_mpi_release (info.n);
3874 gcry_mpi_release (info.e);
3875 return gpg_error (GPG_ERR_GENERAL);
3878 if (*timestamp != info.created_at)
3879 log_info ("Note that the key does not use the suggested creation date\n");
3880 *timestamp = info.created_at;
3882 pk = xcalloc (1, sizeof *pk );
3883 sk = xcalloc (1, sizeof *sk );
3884 sk->timestamp = pk->timestamp = info.created_at;
3885 sk->version = pk->version = 4;
3886 if (expireval)
3887 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
3888 sk->pubkey_algo = pk->pubkey_algo = algo;
3889 pk->pkey[0] = info.n;
3890 pk->pkey[1] = info.e;
3891 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
3892 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
3893 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3894 sk->is_protected = 1;
3895 sk->protect.s2k.mode = 1002;
3896 s = get_parameter_value (para, pSERIALNO);
3897 if (s)
3899 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3900 sk->protect.ivlen++, s += 2)
3901 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3904 if( ret_sk )
3905 *ret_sk = sk;
3907 pkt = xcalloc (1,sizeof *pkt);
3908 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
3909 pkt->pkt.public_key = pk;
3910 add_kbnode(pub_root, new_kbnode( pkt ));
3912 pkt = xcalloc (1,sizeof *pkt);
3913 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
3914 pkt->pkt.secret_key = sk;
3915 add_kbnode(sec_root, new_kbnode( pkt ));
3917 return 0;
3918 #else
3919 return -1;
3920 #endif /*!ENABLE_CARD_SUPPORT*/
3925 static int
3926 gen_card_key_with_backup (int algo, int keyno, int is_primary,
3927 KBNODE pub_root, KBNODE sec_root,
3928 u32 timestamp,
3929 u32 expireval, struct para_data_s *para,
3930 const char *backup_dir)
3932 #ifdef ENABLE_CARD_SUPPORT
3933 int rc;
3934 const char *s;
3935 PACKET *pkt;
3936 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
3937 PKT_public_key *pk;
3938 size_t n;
3939 int i;
3941 rc = generate_raw_key (algo, 1024, timestamp,
3942 &sk_unprotected, &sk_protected);
3943 if (rc)
3944 return rc;
3946 /* First, store the key to the card. */
3947 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
3948 if (rc)
3950 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
3951 free_secret_key (sk_unprotected);
3952 free_secret_key (sk_protected);
3953 return rc;
3956 /* Get rid of the secret key parameters and store the serial numer. */
3957 sk = sk_unprotected;
3958 n = pubkey_get_nskey (sk->pubkey_algo);
3959 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
3961 gcry_mpi_release (sk->skey[i]);
3962 sk->skey[i] = NULL;
3964 i = pubkey_get_npkey (sk->pubkey_algo);
3965 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3966 sk->is_protected = 1;
3967 sk->protect.s2k.mode = 1002;
3968 s = get_parameter_value (para, pSERIALNO);
3969 assert (s);
3970 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3971 sk->protect.ivlen++, s += 2)
3972 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3974 /* Now write the *protected* secret key to the file. */
3976 char name_buffer[50];
3977 char *fname;
3978 IOBUF fp;
3979 mode_t oldmask;
3981 keyid_from_sk (sk, NULL);
3982 sprintf (name_buffer,"sk_%08lX%08lX.gpg",
3983 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
3985 fname = make_filename (backup_dir, name_buffer, NULL);
3986 oldmask = umask (077);
3987 if (is_secured_filename (fname))
3989 fp = NULL;
3990 errno = EPERM;
3992 else
3993 fp = iobuf_create (fname);
3994 umask (oldmask);
3995 if (!fp)
3997 rc = gpg_error_from_syserror ();
3998 log_error (_("can't create backup file `%s': %s\n"),
3999 fname, strerror(errno) );
4000 xfree (fname);
4001 free_secret_key (sk_unprotected);
4002 free_secret_key (sk_protected);
4003 return rc;
4006 pkt = xcalloc (1, sizeof *pkt);
4007 pkt->pkttype = PKT_SECRET_KEY;
4008 pkt->pkt.secret_key = sk_protected;
4009 sk_protected = NULL;
4011 rc = build_packet (fp, pkt);
4012 if (rc)
4014 log_error("build packet failed: %s\n", g10_errstr(rc) );
4015 iobuf_cancel (fp);
4017 else
4019 unsigned char array[MAX_FINGERPRINT_LEN];
4020 char *fprbuf, *p;
4022 iobuf_close (fp);
4023 iobuf_ioctl (NULL, 2, 0, (char*)fname);
4024 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
4026 fingerprint_from_sk (sk, array, &n);
4027 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4028 for (i=0; i < n ; i++, p += 2)
4029 sprintf (p, "%02X", array[i]);
4030 *p++ = ' ';
4031 *p = 0;
4033 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4034 fprbuf,
4035 fname, strlen (fname),
4037 xfree (fprbuf);
4039 free_packet (pkt);
4040 xfree (pkt);
4041 xfree (fname);
4042 if (rc)
4044 free_secret_key (sk_unprotected);
4045 return rc;
4049 /* Create the public key from the secret key. */
4050 pk = xcalloc (1, sizeof *pk );
4051 pk->timestamp = sk->timestamp;
4052 pk->version = sk->version;
4053 if (expireval)
4054 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4055 pk->pubkey_algo = sk->pubkey_algo;
4056 n = pubkey_get_npkey (sk->pubkey_algo);
4057 for (i=0; i < n; i++)
4058 pk->pkey[i] = mpi_copy (sk->skey[i]);
4060 /* Build packets and add them to the node lists. */
4061 pkt = xcalloc (1,sizeof *pkt);
4062 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4063 pkt->pkt.public_key = pk;
4064 add_kbnode(pub_root, new_kbnode( pkt ));
4066 pkt = xcalloc (1,sizeof *pkt);
4067 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4068 pkt->pkt.secret_key = sk;
4069 add_kbnode(sec_root, new_kbnode( pkt ));
4071 return 0;
4072 #else
4073 return -1;
4074 #endif /*!ENABLE_CARD_SUPPORT*/
4078 #ifdef ENABLE_CARD_SUPPORT
4080 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
4082 int rc;
4083 unsigned char *rsa_n = NULL;
4084 unsigned char *rsa_e = NULL;
4085 unsigned char *rsa_p = NULL;
4086 unsigned char *rsa_q = NULL;
4087 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4088 unsigned char *sexp = NULL;
4089 unsigned char *p;
4090 char numbuf[55], numbuf2[50];
4092 assert (is_RSA (sk->pubkey_algo));
4093 assert (!sk->is_protected);
4095 /* Copy the parameters into straight buffers. */
4096 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4097 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4098 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4099 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4100 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4102 rc = G10ERR_INV_ARG;
4103 goto leave;
4106 /* Put the key into an S-expression. */
4107 sexp = p = xmalloc_secure (30
4108 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4109 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4111 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4112 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4113 p = stpcpy (p, numbuf);
4114 memcpy (p, rsa_n, rsa_n_len);
4115 p += rsa_n_len;
4117 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4118 p = stpcpy (p, numbuf);
4119 memcpy (p, rsa_e, rsa_e_len);
4120 p += rsa_e_len;
4122 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4123 p = stpcpy (p, numbuf);
4124 memcpy (p, rsa_p, rsa_p_len);
4125 p += rsa_p_len;
4127 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4128 p = stpcpy (p, numbuf);
4129 memcpy (p, rsa_q, rsa_q_len);
4130 p += rsa_q_len;
4132 p = stpcpy (p,"))(10:created-at");
4133 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4134 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4135 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4137 /* Fixme: Unfortunately we don't have the serialnumber available -
4138 thus we can't pass it down to the agent. */
4139 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4141 leave:
4142 xfree (sexp);
4143 xfree (rsa_n);
4144 xfree (rsa_e);
4145 xfree (rsa_p);
4146 xfree (rsa_q);
4147 return rc;
4149 #endif /*ENABLE_CARD_SUPPORT*/