Doc fixes.
[gnupg.git] / g10 / keygen.c
blob6a37471cb94312b69b258ad6130fbbd205a6eecf
1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
32 #include "gpg.h"
33 #include "util.h"
34 #include "main.h"
35 #include "packet.h"
36 #include "cipher.h"
37 #include "ttyio.h"
38 #include "options.h"
39 #include "keydb.h"
40 #include "trustdb.h"
41 #include "status.h"
42 #include "i18n.h"
43 #include "keyserver-internal.h"
44 #include "call-agent.h"
47 #define MAX_PREFS 30
49 enum para_name {
50 pKEYTYPE,
51 pKEYLENGTH,
52 pKEYUSAGE,
53 pSUBKEYTYPE,
54 pSUBKEYLENGTH,
55 pSUBKEYUSAGE,
56 pAUTHKEYTYPE,
57 pNAMEREAL,
58 pNAMEEMAIL,
59 pNAMECOMMENT,
60 pPREFERENCES,
61 pREVOKER,
62 pUSERID,
63 pCREATIONDATE,
64 pKEYCREATIONDATE, /* Same in seconds since epoch. */
65 pEXPIREDATE,
66 pKEYEXPIRE, /* in n seconds */
67 pSUBKEYEXPIRE, /* in n seconds */
68 pPASSPHRASE,
69 pPASSPHRASE_DEK,
70 pPASSPHRASE_S2K,
71 pSERIALNO,
72 pBACKUPENCDIR,
73 pHANDLE,
74 pKEYSERVER
77 struct para_data_s {
78 struct para_data_s *next;
79 int lnr;
80 enum para_name key;
81 union {
82 DEK *dek;
83 STRING2KEY *s2k;
84 u32 expire;
85 u32 creation;
86 unsigned int usage;
87 struct revocation_key revkey;
88 char value[1];
89 } u;
92 struct output_control_s {
93 int lnr;
94 int dryrun;
95 int ask_passphrase;
96 int use_files;
97 struct {
98 char *fname;
99 char *newfname;
100 IOBUF stream;
101 armor_filter_context_t *afx;
102 } pub;
103 struct {
104 char *fname;
105 char *newfname;
106 IOBUF stream;
107 armor_filter_context_t *afx;
108 } sec;
112 struct opaque_data_usage_and_pk {
113 unsigned int usage;
114 PKT_public_key *pk;
118 static int prefs_initialized = 0;
119 static byte sym_prefs[MAX_PREFS];
120 static int nsym_prefs;
121 static byte hash_prefs[MAX_PREFS];
122 static int nhash_prefs;
123 static byte zip_prefs[MAX_PREFS];
124 static int nzip_prefs;
125 static int mdc_available,ks_modify;
127 static void do_generate_keypair( struct para_data_s *para,
128 struct output_control_s *outctrl, int card );
129 static int write_keyblock( IOBUF out, KBNODE node );
130 static int gen_card_key (int algo, int keyno, int is_primary,
131 KBNODE pub_root, KBNODE sec_root,
132 PKT_secret_key **ret_sk,
133 u32 *timestamp,
134 u32 expireval, struct para_data_s *para);
135 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
136 KBNODE pub_root, KBNODE sec_root,
137 u32 timestamp,
138 u32 expireval, struct para_data_s *para,
139 const char *backup_dir);
142 static void
143 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
145 byte array[MAX_FINGERPRINT_LEN], *s;
146 char *buf, *p;
147 size_t i, n;
149 if (!handle)
150 handle = "";
152 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
154 p = buf;
155 if (letter || pk)
157 *p++ = letter;
158 *p++ = ' ';
159 fingerprint_from_pk (pk, array, &n);
160 s = array;
161 for (i=0; i < n ; i++, s++, p += 2)
162 sprintf (p, "%02X", *s);
164 if (*handle)
166 *p++ = ' ';
167 for (i=0; handle[i] && i < 100; i++)
168 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
170 *p = 0;
171 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
172 buf);
173 xfree (buf);
176 static void
177 print_status_key_not_created (const char *handle)
179 print_status_key_created (0, NULL, handle);
184 static void
185 write_uid( KBNODE root, const char *s )
187 PACKET *pkt = xmalloc_clear(sizeof *pkt );
188 size_t n = strlen(s);
190 pkt->pkttype = PKT_USER_ID;
191 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
192 pkt->pkt.user_id->len = n;
193 pkt->pkt.user_id->ref = 1;
194 strcpy(pkt->pkt.user_id->name, s);
195 add_kbnode( root, new_kbnode( pkt ) );
198 static void
199 do_add_key_flags (PKT_signature *sig, unsigned int use)
201 byte buf[1];
203 buf[0] = 0;
205 /* The spec says that all primary keys MUST be able to certify. */
206 if(sig->sig_class!=0x18)
207 buf[0] |= 0x01;
209 if (use & PUBKEY_USAGE_SIG)
210 buf[0] |= 0x02;
211 if (use & PUBKEY_USAGE_ENC)
212 buf[0] |= 0x04 | 0x08;
213 if (use & PUBKEY_USAGE_AUTH)
214 buf[0] |= 0x20;
216 if (!buf[0])
217 return;
219 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
224 keygen_add_key_expire( PKT_signature *sig, void *opaque )
226 PKT_public_key *pk = opaque;
227 byte buf[8];
228 u32 u;
230 if( pk->expiredate ) {
231 if(pk->expiredate > pk->timestamp)
232 u= pk->expiredate - pk->timestamp;
233 else
234 u= 1;
236 buf[0] = (u >> 24) & 0xff;
237 buf[1] = (u >> 16) & 0xff;
238 buf[2] = (u >> 8) & 0xff;
239 buf[3] = u & 0xff;
240 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
242 else
244 /* Make sure we don't leave a key expiration subpacket lying
245 around */
246 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
249 return 0;
252 static int
253 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
255 struct opaque_data_usage_and_pk *oduap = opaque;
257 do_add_key_flags (sig, oduap->usage);
258 return keygen_add_key_expire (sig, oduap->pk);
261 static int
262 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
264 int i;
266 for (i=0; i < *nbuf; i++ )
267 if (buf[i] == val)
269 log_info (_("preference `%s' duplicated\n"), item);
270 return -1;
273 if (*nbuf >= MAX_PREFS)
275 if(type==1)
276 log_info(_("too many cipher preferences\n"));
277 else if(type==2)
278 log_info(_("too many digest preferences\n"));
279 else if(type==3)
280 log_info(_("too many compression preferences\n"));
281 else
282 BUG();
284 return -1;
287 buf[(*nbuf)++] = val;
288 return 0;
292 * Parse the supplied string and use it to set the standard
293 * preferences. The string may be in a form like the one printed by
294 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
295 * cipher/hash/compress names. Use NULL to set the default
296 * preferences. Returns: 0 = okay
299 keygen_set_std_prefs (const char *string,int personal)
301 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
302 int nsym=0, nhash=0, nzip=0, val, rc=0;
303 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
304 char dummy_string[45+1]; /* Enough for 15 items. */
306 if (!string || !ascii_strcasecmp (string, "default"))
308 if (opt.def_preference_list)
309 string=opt.def_preference_list;
310 else
312 dummy_string[0]='\0';
314 /* The rationale why we use the order AES256,192,128 is
315 for compatibility reasons with PGP. If gpg would
316 define AES128 first, we would get the somewhat
317 confusing situation:
319 gpg -r pgpkey -r gpgkey ---gives--> AES256
320 gpg -r gpgkey -r pgpkey ---gives--> AES
322 Note that by using --personal-cipher-preferences it is
323 possible to prefer AES128.
326 /* Make sure we do not add more than 15 items here, as we
327 could overflow the size of dummy_string. We currently
328 have at most 12. */
329 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
330 strcat(dummy_string,"S9 ");
331 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
332 strcat(dummy_string,"S8 ");
333 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
334 strcat(dummy_string,"S7 ");
335 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
336 strcat(dummy_string,"S3 ");
337 strcat(dummy_string,"S2 "); /* 3DES */
338 /* If we have it, IDEA goes *after* 3DES so it won't be
339 used unless we're encrypting along with a V3 key.
340 Ideally, we would only put the S1 preference in if the
341 key was RSA and <=2048 bits, as that is what won't
342 break PGP2, but that is difficult with the current
343 code, and not really worth checking as a non-RSA <=2048
344 bit key wouldn't be usable by PGP2 anyway. -dms */
345 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
346 strcat(dummy_string,"S1 ");
348 /* SHA-1 */
349 strcat(dummy_string,"H2 ");
351 if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256))
352 strcat(dummy_string,"H8 ");
354 /* RIPEMD160 */
355 if (!openpgp_md_test_algo(DIGEST_ALGO_RMD160))
356 strcat(dummy_string,"H3 ");
358 /* ZLIB */
359 strcat(dummy_string,"Z2 ");
361 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
362 strcat(dummy_string,"Z3 ");
364 /* ZIP */
365 strcat(dummy_string,"Z1");
367 string=dummy_string;
370 else if (!ascii_strcasecmp (string, "none"))
371 string = "";
373 if(strlen(string))
375 char *tok,*prefstring;
377 prefstring=xstrdup(string); /* need a writable string! */
379 while((tok=strsep(&prefstring," ,")))
381 if((val=string_to_cipher_algo (tok)))
383 if(set_one_pref(val,1,tok,sym,&nsym))
384 rc=-1;
386 else if((val=string_to_digest_algo (tok)))
388 if(set_one_pref(val,2,tok,hash,&nhash))
389 rc=-1;
391 else if((val=string_to_compress_algo(tok))>-1)
393 if(set_one_pref(val,3,tok,zip,&nzip))
394 rc=-1;
396 else if (ascii_strcasecmp(tok,"mdc")==0)
397 mdc=1;
398 else if (ascii_strcasecmp(tok,"no-mdc")==0)
399 mdc=0;
400 else if (ascii_strcasecmp(tok,"ks-modify")==0)
401 modify=1;
402 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
403 modify=0;
404 else
406 log_info (_("invalid item `%s' in preference string\n"),tok);
408 /* Complain if IDEA is not available. */
409 if(ascii_strcasecmp(tok,"s1")==0
410 || ascii_strcasecmp(tok,"idea")==0)
411 idea_cipher_warn(1);
413 rc=-1;
417 xfree(prefstring);
420 if(!rc)
422 if(personal)
424 if(personal==PREFTYPE_SYM)
426 xfree(opt.personal_cipher_prefs);
428 if(nsym==0)
429 opt.personal_cipher_prefs=NULL;
430 else
432 int i;
434 opt.personal_cipher_prefs=
435 xmalloc(sizeof(prefitem_t *)*(nsym+1));
437 for (i=0; i<nsym; i++)
439 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
440 opt.personal_cipher_prefs[i].value = sym[i];
443 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
444 opt.personal_cipher_prefs[i].value = 0;
447 else if(personal==PREFTYPE_HASH)
449 xfree(opt.personal_digest_prefs);
451 if(nhash==0)
452 opt.personal_digest_prefs=NULL;
453 else
455 int i;
457 opt.personal_digest_prefs=
458 xmalloc(sizeof(prefitem_t *)*(nhash+1));
460 for (i=0; i<nhash; i++)
462 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
463 opt.personal_digest_prefs[i].value = hash[i];
466 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
467 opt.personal_digest_prefs[i].value = 0;
470 else if(personal==PREFTYPE_ZIP)
472 xfree(opt.personal_compress_prefs);
474 if(nzip==0)
475 opt.personal_compress_prefs=NULL;
476 else
478 int i;
480 opt.personal_compress_prefs=
481 xmalloc(sizeof(prefitem_t *)*(nzip+1));
483 for (i=0; i<nzip; i++)
485 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
486 opt.personal_compress_prefs[i].value = zip[i];
489 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
490 opt.personal_compress_prefs[i].value = 0;
494 else
496 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
497 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
498 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
499 mdc_available = mdc;
500 ks_modify = modify;
501 prefs_initialized = 1;
505 return rc;
508 /* Return a fake user ID containing the preferences. Caller must
509 free. */
510 PKT_user_id *keygen_get_std_prefs(void)
512 int i,j=0;
513 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
515 if(!prefs_initialized)
516 keygen_set_std_prefs(NULL,0);
518 uid->ref=1;
520 uid->prefs=xmalloc((sizeof(prefitem_t *)*
521 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
523 for(i=0;i<nsym_prefs;i++,j++)
525 uid->prefs[j].type=PREFTYPE_SYM;
526 uid->prefs[j].value=sym_prefs[i];
529 for(i=0;i<nhash_prefs;i++,j++)
531 uid->prefs[j].type=PREFTYPE_HASH;
532 uid->prefs[j].value=hash_prefs[i];
535 for(i=0;i<nzip_prefs;i++,j++)
537 uid->prefs[j].type=PREFTYPE_ZIP;
538 uid->prefs[j].value=zip_prefs[i];
541 uid->prefs[j].type=PREFTYPE_NONE;
542 uid->prefs[j].value=0;
544 uid->flags.mdc=mdc_available;
545 uid->flags.ks_modify=ks_modify;
547 return uid;
550 static void
551 add_feature_mdc (PKT_signature *sig,int enabled)
553 const byte *s;
554 size_t n;
555 int i;
556 char *buf;
558 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
559 /* Already set or cleared */
560 if (s && n &&
561 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
562 return;
564 if (!s || !n) { /* create a new one */
565 n = 1;
566 buf = xmalloc_clear (n);
568 else {
569 buf = xmalloc (n);
570 memcpy (buf, s, n);
573 if(enabled)
574 buf[0] |= 0x01; /* MDC feature */
575 else
576 buf[0] &= ~0x01;
578 /* Are there any bits set? */
579 for(i=0;i<n;i++)
580 if(buf[i]!=0)
581 break;
583 if(i==n)
584 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
585 else
586 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
588 xfree (buf);
591 static void
592 add_keyserver_modify (PKT_signature *sig,int enabled)
594 const byte *s;
595 size_t n;
596 int i;
597 char *buf;
599 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
600 enabled=!enabled;
602 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
603 /* Already set or cleared */
604 if (s && n &&
605 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
606 return;
608 if (!s || !n) { /* create a new one */
609 n = 1;
610 buf = xmalloc_clear (n);
612 else {
613 buf = xmalloc (n);
614 memcpy (buf, s, n);
617 if(enabled)
618 buf[0] |= 0x80; /* no-modify flag */
619 else
620 buf[0] &= ~0x80;
622 /* Are there any bits set? */
623 for(i=0;i<n;i++)
624 if(buf[i]!=0)
625 break;
627 if(i==n)
628 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
629 else
630 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
632 xfree (buf);
637 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
639 (void)opaque;
641 if (!prefs_initialized)
642 keygen_set_std_prefs (NULL, 0);
644 if (nsym_prefs)
645 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
646 else
648 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
649 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
652 if (nhash_prefs)
653 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
654 else
656 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
657 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
660 if (nzip_prefs)
661 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
662 else
664 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
665 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
668 /* Make sure that the MDC feature flag is set if needed. */
669 add_feature_mdc (sig,mdc_available);
670 add_keyserver_modify (sig,ks_modify);
671 keygen_add_keyserver_url(sig,NULL);
673 return 0;
677 /****************
678 * Add preference to the self signature packet.
679 * This is only called for packets with version > 3.
683 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
685 PKT_public_key *pk = opaque;
687 do_add_key_flags (sig, pk->pubkey_usage);
688 keygen_add_key_expire( sig, opaque );
689 keygen_upd_std_prefs (sig, opaque);
690 keygen_add_keyserver_url(sig,NULL);
692 return 0;
696 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
698 const char *url=opaque;
700 if(!url)
701 url=opt.def_keyserver_url;
703 if(url)
704 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
705 else
706 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
708 return 0;
712 keygen_add_notations(PKT_signature *sig,void *opaque)
714 struct notation *notation;
716 /* We always start clean */
717 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
718 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
719 sig->flags.notation=0;
721 for(notation=opaque;notation;notation=notation->next)
722 if(!notation->flags.ignore)
724 unsigned char *buf;
725 unsigned int n1,n2;
727 n1=strlen(notation->name);
728 if(notation->altvalue)
729 n2=strlen(notation->altvalue);
730 else if(notation->bdat)
731 n2=notation->blen;
732 else
733 n2=strlen(notation->value);
735 buf = xmalloc( 8 + n1 + n2 );
737 /* human readable or not */
738 buf[0] = notation->bdat?0:0x80;
739 buf[1] = buf[2] = buf[3] = 0;
740 buf[4] = n1 >> 8;
741 buf[5] = n1;
742 buf[6] = n2 >> 8;
743 buf[7] = n2;
744 memcpy(buf+8, notation->name, n1 );
745 if(notation->altvalue)
746 memcpy(buf+8+n1, notation->altvalue, n2 );
747 else if(notation->bdat)
748 memcpy(buf+8+n1, notation->bdat, n2 );
749 else
750 memcpy(buf+8+n1, notation->value, n2 );
751 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
752 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
753 buf, 8+n1+n2 );
754 xfree(buf);
757 return 0;
761 keygen_add_revkey(PKT_signature *sig, void *opaque)
763 struct revocation_key *revkey=opaque;
764 byte buf[2+MAX_FINGERPRINT_LEN];
766 buf[0]=revkey->class;
767 buf[1]=revkey->algid;
768 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
770 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
772 /* All sigs with revocation keys set are nonrevocable */
773 sig->flags.revocable=0;
774 buf[0] = 0;
775 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
777 parse_revkeys(sig);
779 return 0;
784 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
785 signature creation time. */
787 make_backsig (PKT_signature *sig,PKT_public_key *pk,
788 PKT_public_key *sub_pk,PKT_secret_key *sub_sk,
789 u32 timestamp)
791 PKT_signature *backsig;
792 int rc;
794 cache_public_key(sub_pk);
796 rc = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_sk, 0x19,
797 0, 0, timestamp, 0, NULL, NULL);
798 if(rc)
799 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
800 else
802 /* Get it into a binary packed form. */
803 IOBUF backsig_out=iobuf_temp();
804 PACKET backsig_pkt;
806 init_packet(&backsig_pkt);
807 backsig_pkt.pkttype=PKT_SIGNATURE;
808 backsig_pkt.pkt.signature=backsig;
809 rc=build_packet(backsig_out,&backsig_pkt);
810 free_packet(&backsig_pkt);
811 if(rc)
812 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
813 else
815 size_t pktlen=0;
816 byte *buf=iobuf_get_temp_buffer(backsig_out);
818 /* Remove the packet header */
819 if(buf[0]&0x40)
821 if(buf[1]<192)
823 pktlen=buf[1];
824 buf+=2;
826 else if(buf[1]<224)
828 pktlen=(buf[1]-192)*256;
829 pktlen+=buf[2]+192;
830 buf+=3;
832 else if(buf[1]==255)
834 pktlen =buf[2] << 24;
835 pktlen|=buf[3] << 16;
836 pktlen|=buf[4] << 8;
837 pktlen|=buf[5];
838 buf+=6;
840 else
841 BUG();
843 else
845 int mark=1;
847 switch(buf[0]&3)
849 case 3:
850 BUG();
851 break;
853 case 2:
854 pktlen =buf[mark++] << 24;
855 pktlen|=buf[mark++] << 16;
857 case 1:
858 pktlen|=buf[mark++] << 8;
860 case 0:
861 pktlen|=buf[mark++];
864 buf+=mark;
867 /* Now make the binary blob into a subpacket. */
868 build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
870 iobuf_close(backsig_out);
874 return rc;
878 static int
879 write_direct_sig (KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
880 struct revocation_key *revkey, u32 timestamp)
882 PACKET *pkt;
883 PKT_signature *sig;
884 int rc=0;
885 KBNODE node;
886 PKT_public_key *pk;
888 if( opt.verbose )
889 log_info(_("writing direct signature\n"));
891 /* Get the pk packet from the pub_tree. */
892 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
893 if( !node )
894 BUG();
895 pk = node->pkt->pkt.public_key;
897 /* We have to cache the key, so that the verification of the
898 signature creation is able to retrieve the public key. */
899 cache_public_key (pk);
901 /* Make the signature. */
902 rc = make_keysig_packet (&sig,pk,NULL,NULL,sk,0x1F,
903 0, 0, timestamp, 0,
904 keygen_add_revkey, revkey);
905 if( rc )
907 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
908 return rc;
911 pkt = xmalloc_clear( sizeof *pkt );
912 pkt->pkttype = PKT_SIGNATURE;
913 pkt->pkt.signature = sig;
914 add_kbnode( root, new_kbnode( pkt ) );
915 return rc;
919 static int
920 write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
921 unsigned int use, u32 timestamp )
923 PACKET *pkt;
924 PKT_signature *sig;
925 PKT_user_id *uid;
926 int rc=0;
927 KBNODE node;
928 PKT_public_key *pk;
930 if( opt.verbose )
931 log_info(_("writing self signature\n"));
933 /* Get the uid packet from the list. */
934 node = find_kbnode( pub_root, PKT_USER_ID );
935 if( !node )
936 BUG(); /* No user id packet in tree. */
937 uid = node->pkt->pkt.user_id;
939 /* Get the pk packet from the pub_tree. */
940 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
941 if( !node )
942 BUG();
943 pk = node->pkt->pkt.public_key;
944 pk->pubkey_usage = use;
946 /* We have to cache the key, so that the verification of the
947 signature creation is able to retrieve the public key. */
948 cache_public_key (pk);
950 /* Make the signature. */
951 rc = make_keysig_packet (&sig, pk, uid, NULL, sk, 0x13,
952 0, 0, timestamp, 0,
953 keygen_add_std_prefs, pk);
954 if( rc )
956 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
957 return rc;
960 pkt = xmalloc_clear( sizeof *pkt );
961 pkt->pkttype = PKT_SIGNATURE;
962 pkt->pkt.signature = sig;
963 add_kbnode( sec_root, new_kbnode( pkt ) );
965 pkt = xmalloc_clear( sizeof *pkt );
966 pkt->pkttype = PKT_SIGNATURE;
967 pkt->pkt.signature = copy_signature(NULL,sig);
968 add_kbnode( pub_root, new_kbnode( pkt ) );
969 return rc;
973 /* Write the key binding signature. If TIMESTAMP is not NULL use the
974 signature creation times. */
975 static int
976 write_keybinding (KBNODE root, KBNODE pub_root,
977 PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
978 unsigned int use, u32 timestamp)
980 PACKET *pkt;
981 PKT_signature *sig;
982 int rc=0;
983 KBNODE node;
984 PKT_public_key *pri_pk, *sub_pk;
985 struct opaque_data_usage_and_pk oduap;
987 if ( opt.verbose )
988 log_info(_("writing key binding signature\n"));
990 /* Get the pk packet from the pub_tree. */
991 node = find_kbnode ( pub_root, PKT_PUBLIC_KEY );
992 if ( !node )
993 BUG();
994 pri_pk = node->pkt->pkt.public_key;
996 /* We have to cache the key, so that the verification of the
997 * signature creation is able to retrieve the public key. */
998 cache_public_key (pri_pk);
1000 /* Find the last subkey. */
1001 sub_pk = NULL;
1002 for (node=pub_root; node; node = node->next )
1004 if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
1005 sub_pk = node->pkt->pkt.public_key;
1007 if (!sub_pk)
1008 BUG();
1010 /* Make the signature. */
1011 oduap.usage = use;
1012 oduap.pk = sub_pk;
1013 rc = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18,
1014 0, 0, timestamp, 0,
1015 keygen_add_key_flags_and_expire, &oduap );
1016 if (rc)
1018 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc) );
1019 return rc;
1022 /* Make a backsig. */
1023 if (use&PUBKEY_USAGE_SIG)
1025 rc = make_backsig (sig, pri_pk, sub_pk, sub_sk, timestamp);
1026 if (rc)
1027 return rc;
1030 pkt = xmalloc_clear ( sizeof *pkt );
1031 pkt->pkttype = PKT_SIGNATURE;
1032 pkt->pkt.signature = sig;
1033 add_kbnode (root, new_kbnode (pkt) );
1034 return rc;
1039 static int
1040 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1041 const char *topname, const char *elems)
1043 gcry_sexp_t list, l2;
1044 const char *s;
1045 int i, idx;
1046 int rc = 0;
1048 list = gcry_sexp_find_token (sexp, topname, 0);
1049 if (!list)
1050 return gpg_error (GPG_ERR_INV_OBJ);
1051 l2 = gcry_sexp_cadr (list);
1052 gcry_sexp_release (list);
1053 list = l2;
1054 if (!list)
1055 return gpg_error (GPG_ERR_NO_OBJ);
1057 for (idx=0,s=elems; *s; s++, idx++)
1059 l2 = gcry_sexp_find_token (list, s, 1);
1060 if (!l2)
1062 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1063 goto leave;
1065 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1066 gcry_sexp_release (l2);
1067 if (!array[idx])
1069 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1070 goto leave;
1073 gcry_sexp_release (list);
1075 leave:
1076 if (rc)
1078 for (i=0; i<idx; i++)
1080 xfree (array[i]);
1081 array[i] = NULL;
1083 gcry_sexp_release (list);
1085 return rc;
1089 static int
1090 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
1092 int rc = 0;
1094 if (dek)
1096 sk->protect.algo = dek->algo;
1097 sk->protect.s2k = *s2k;
1098 rc = protect_secret_key (sk, dek);
1099 if (rc)
1100 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
1103 return rc;
1106 static void
1107 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
1109 (void)misc_key_info;
1110 (void)sec_root;
1111 #if 0 /* Not used anymore */
1112 size_t n;
1113 char *buf;
1115 if (misc_key_info)
1117 /* DSA: don't know whether it makes sense to have the factors, so for now
1118 we store them in the secret keyring (but they are not secret)
1119 p = 2 * q * f1 * f2 * ... * fn
1120 We store only f1 to f_n-1; fn can be calculated because p and q
1121 are known. */
1122 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
1123 buf = xmalloc (n+4);
1124 strcpy (buf, "#::");
1125 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
1126 if (n)
1128 n += 3;
1129 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
1131 xfree (buf);
1132 gcry_sexp_release (misc_key_info);
1134 #endif
1138 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1139 time to be put into the key structure. */
1140 static int
1141 gen_elg (int algo, unsigned int nbits,
1142 KBNODE pub_root, KBNODE sec_root, DEK *dek,
1143 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1144 u32 timestamp, u32 expireval, int is_subkey)
1146 int rc;
1147 PACKET *pkt;
1148 PKT_secret_key *sk;
1149 PKT_public_key *pk;
1150 gcry_sexp_t s_parms, s_key;
1151 gcry_sexp_t misc_key_info;
1153 assert( is_ELGAMAL(algo) );
1155 if (nbits < 512)
1157 nbits = 1024;
1158 log_info (_("keysize invalid; using %u bits\n"), nbits );
1161 if ((nbits % 32))
1163 nbits = ((nbits + 31) / 32) * 32;
1164 log_info (_("keysize rounded up to %u bits\n"), nbits );
1168 rc = gcry_sexp_build ( &s_parms, NULL,
1169 "(genkey(%s(nbits %d)))",
1170 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1171 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1172 (int)nbits);
1173 if (rc)
1174 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1176 rc = gcry_pk_genkey (&s_key, s_parms);
1177 gcry_sexp_release (s_parms);
1178 if (rc)
1180 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1181 return rc;
1184 sk = xmalloc_clear( sizeof *sk );
1185 pk = xmalloc_clear( sizeof *pk );
1186 sk->timestamp = pk->timestamp = timestamp;
1187 sk->version = pk->version = 4;
1188 if (expireval)
1190 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1192 sk->pubkey_algo = pk->pubkey_algo = algo;
1194 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
1195 if (rc)
1197 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1198 gcry_sexp_release (s_key);
1199 free_secret_key (sk);
1200 free_public_key (pk);
1201 return rc;
1203 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
1204 if (rc)
1206 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1207 gcry_sexp_release (s_key);
1208 free_secret_key (sk);
1209 free_public_key (pk);
1210 return rc;
1212 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1213 gcry_sexp_release (s_key);
1215 sk->is_protected = 0;
1216 sk->protect.algo = 0;
1218 sk->csum = checksum_mpi (sk->skey[3]);
1219 if (ret_sk) /* Return an unprotected version of the sk. */
1220 *ret_sk = copy_secret_key ( NULL, sk );
1222 rc = genhelp_protect (dek, s2k, sk);
1223 if (rc)
1225 free_public_key (pk);
1226 free_secret_key (sk);
1227 gcry_sexp_release (misc_key_info);
1228 return rc;
1231 pkt = xmalloc_clear (sizeof *pkt);
1232 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1233 pkt->pkt.public_key = pk;
1234 add_kbnode (pub_root, new_kbnode( pkt ));
1236 /* Don't know whether it makes sense to have access to the factors,
1237 so for now we store them in the secret keyring (but they are not
1238 secret). */
1239 pkt = xmalloc_clear (sizeof *pkt);
1240 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1241 pkt->pkt.secret_key = sk;
1242 add_kbnode (sec_root, new_kbnode( pkt ));
1244 genhelp_factors (misc_key_info, sec_root);
1246 return 0;
1250 /****************
1251 * Generate a DSA key
1253 static int
1254 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1255 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1256 u32 timestamp, u32 expireval, int is_subkey)
1258 int rc;
1259 PACKET *pkt;
1260 PKT_secret_key *sk;
1261 PKT_public_key *pk;
1262 gcry_sexp_t s_parms, s_key;
1263 gcry_sexp_t misc_key_info;
1264 unsigned int qbits;
1266 if ( nbits < 512 || (!opt.flags.dsa2 && nbits > 1024))
1268 nbits = 1024;
1269 log_info(_("keysize invalid; using %u bits\n"), nbits );
1271 else if ( nbits > 3072 )
1273 nbits = 3072;
1274 log_info(_("keysize invalid; using %u bits\n"), nbits );
1277 if( (nbits % 64) )
1279 nbits = ((nbits + 63) / 64) * 64;
1280 log_info(_("keysize rounded up to %u bits\n"), nbits );
1284 Figure out a q size based on the key size. FIPS 180-3 says:
1286 L = 1024, N = 160
1287 L = 2048, N = 224
1288 L = 2048, N = 256
1289 L = 3072, N = 256
1291 2048/256 is an odd pair since there is also a 2048/224 and
1292 3072/256. Matching sizes is not a very exact science.
1294 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1295 but less than 2048, and 160 for 1024 (DSA1).
1298 if (nbits > 2048)
1299 qbits = 256;
1300 else if ( nbits > 1024)
1301 qbits = 224;
1302 else
1303 qbits = 160;
1305 if (qbits != 160 )
1306 log_info (_("WARNING: some OpenPGP programs can't"
1307 " handle a DSA key with this digest size\n"));
1309 rc = gcry_sexp_build (&s_parms, NULL,
1310 "(genkey(dsa(nbits %d)(qbits %d)))",
1311 (int)nbits, (int)qbits);
1312 if (rc)
1313 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1315 rc = gcry_pk_genkey (&s_key, s_parms);
1316 gcry_sexp_release (s_parms);
1317 if (rc)
1319 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1320 return rc;
1323 sk = xmalloc_clear( sizeof *sk );
1324 pk = xmalloc_clear( sizeof *pk );
1325 sk->timestamp = pk->timestamp = timestamp;
1326 sk->version = pk->version = 4;
1327 if (expireval)
1328 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1329 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1331 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1332 if (rc)
1334 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1335 gcry_sexp_release (s_key);
1336 free_public_key(pk);
1337 free_secret_key(sk);
1338 return rc;
1340 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1341 if (rc)
1343 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1344 gcry_sexp_release (s_key);
1345 free_public_key(pk);
1346 free_secret_key(sk);
1347 return rc;
1349 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1350 gcry_sexp_release (s_key);
1352 sk->is_protected = 0;
1353 sk->protect.algo = 0;
1355 sk->csum = checksum_mpi ( sk->skey[4] );
1356 if( ret_sk ) /* return an unprotected version of the sk */
1357 *ret_sk = copy_secret_key( NULL, sk );
1359 rc = genhelp_protect (dek, s2k, sk);
1360 if (rc)
1362 free_public_key (pk);
1363 free_secret_key (sk);
1364 gcry_sexp_release (misc_key_info);
1365 return rc;
1368 pkt = xmalloc_clear(sizeof *pkt);
1369 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1370 pkt->pkt.public_key = pk;
1371 add_kbnode(pub_root, new_kbnode( pkt ));
1373 /* Don't know whether it makes sense to have the factors, so for now
1374 * we store them in the secret keyring (but they are not secret)
1375 * p = 2 * q * f1 * f2 * ... * fn
1376 * We store only f1 to f_n-1; fn can be calculated because p and q
1377 * are known.
1379 pkt = xmalloc_clear(sizeof *pkt);
1380 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1381 pkt->pkt.secret_key = sk;
1382 add_kbnode(sec_root, new_kbnode( pkt ));
1384 genhelp_factors (misc_key_info, sec_root);
1386 return 0;
1391 * Generate an RSA key.
1393 static int
1394 gen_rsa (int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1395 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1396 u32 timestamp, u32 expireval, int is_subkey)
1398 int rc;
1399 PACKET *pkt;
1400 PKT_secret_key *sk;
1401 PKT_public_key *pk;
1402 gcry_sexp_t s_parms, s_key;
1404 assert (is_RSA(algo));
1406 if (nbits < 1024)
1408 nbits = 1024;
1409 log_info (_("keysize invalid; using %u bits\n"), nbits );
1412 if ((nbits % 32))
1414 nbits = ((nbits + 31) / 32) * 32;
1415 log_info (_("keysize rounded up to %u bits\n"), nbits );
1418 rc = gcry_sexp_build (&s_parms, NULL,
1419 "(genkey(rsa(nbits %d)))",
1420 (int)nbits);
1421 if (rc)
1422 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1424 rc = gcry_pk_genkey (&s_key, s_parms);
1425 gcry_sexp_release (s_parms);
1426 if (rc)
1428 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1429 return rc;
1432 sk = xmalloc_clear( sizeof *sk );
1433 pk = xmalloc_clear( sizeof *pk );
1434 sk->timestamp = pk->timestamp = timestamp;
1435 sk->version = pk->version = 4;
1436 if (expireval)
1438 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1440 sk->pubkey_algo = pk->pubkey_algo = algo;
1442 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1443 if (rc)
1445 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1446 gcry_sexp_release (s_key);
1447 free_public_key(pk);
1448 free_secret_key(sk);
1449 return rc;
1451 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1452 if (rc)
1454 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1455 gcry_sexp_release (s_key);
1456 free_public_key(pk);
1457 free_secret_key(sk);
1458 return rc;
1460 gcry_sexp_release (s_key);
1462 sk->is_protected = 0;
1463 sk->protect.algo = 0;
1465 sk->csum = checksum_mpi (sk->skey[2] );
1466 sk->csum += checksum_mpi (sk->skey[3] );
1467 sk->csum += checksum_mpi (sk->skey[4] );
1468 sk->csum += checksum_mpi (sk->skey[5] );
1469 if( ret_sk ) /* return an unprotected version of the sk */
1470 *ret_sk = copy_secret_key( NULL, sk );
1472 rc = genhelp_protect (dek, s2k, sk);
1473 if (rc)
1475 free_public_key (pk);
1476 free_secret_key (sk);
1477 return rc;
1480 pkt = xmalloc_clear(sizeof *pkt);
1481 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1482 pkt->pkt.public_key = pk;
1483 add_kbnode(pub_root, new_kbnode( pkt ));
1485 pkt = xmalloc_clear(sizeof *pkt);
1486 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1487 pkt->pkt.secret_key = sk;
1488 add_kbnode(sec_root, new_kbnode( pkt ));
1490 return 0;
1494 /****************
1495 * check valid days:
1496 * return 0 on error or the multiplier
1498 static int
1499 check_valid_days( const char *s )
1501 if( !digitp(s) )
1502 return 0;
1503 for( s++; *s; s++)
1504 if( !digitp(s) )
1505 break;
1506 if( !*s )
1507 return 1;
1508 if( s[1] )
1509 return 0; /* e.g. "2323wc" */
1510 if( *s == 'd' || *s == 'D' )
1511 return 1;
1512 if( *s == 'w' || *s == 'W' )
1513 return 7;
1514 if( *s == 'm' || *s == 'M' )
1515 return 30;
1516 if( *s == 'y' || *s == 'Y' )
1517 return 365;
1518 return 0;
1522 static void
1523 print_key_flags(int flags)
1525 if(flags&PUBKEY_USAGE_SIG)
1526 tty_printf("%s ",_("Sign"));
1528 if(flags&PUBKEY_USAGE_CERT)
1529 tty_printf("%s ",_("Certify"));
1531 if(flags&PUBKEY_USAGE_ENC)
1532 tty_printf("%s ",_("Encrypt"));
1534 if(flags&PUBKEY_USAGE_AUTH)
1535 tty_printf("%s ",_("Authenticate"));
1539 /* Returns the key flags */
1540 static unsigned int
1541 ask_key_flags(int algo,int subkey)
1543 /* TRANSLATORS: Please use only plain ASCII characters for the
1544 translation. If this is not possible use single digits. The
1545 string needs to 8 bytes long. Here is a description of the
1546 functions:
1548 s = Toggle signing capability
1549 e = Toggle encryption capability
1550 a = Toggle authentication capability
1551 q = Finish
1553 const char *togglers=_("SsEeAaQq");
1554 char *answer=NULL;
1555 unsigned int current=0;
1556 unsigned int possible=openpgp_pk_algo_usage(algo);
1558 if ( strlen(togglers) != 7 )
1560 tty_printf ("NOTE: Bad translation at %s:%d. "
1561 "Please report.\n", __FILE__, __LINE__);
1562 togglers = "11223300";
1565 /* Only primary keys may certify. */
1566 if(subkey)
1567 possible&=~PUBKEY_USAGE_CERT;
1569 /* Preload the current set with the possible set, minus
1570 authentication, since nobody really uses auth yet. */
1571 current=possible&~PUBKEY_USAGE_AUTH;
1573 for(;;)
1575 tty_printf("\n");
1576 tty_printf(_("Possible actions for a %s key: "),
1577 gcry_pk_algo_name (algo));
1578 print_key_flags(possible);
1579 tty_printf("\n");
1580 tty_printf(_("Current allowed actions: "));
1581 print_key_flags(current);
1582 tty_printf("\n\n");
1584 if(possible&PUBKEY_USAGE_SIG)
1585 tty_printf(_(" (%c) Toggle the sign capability\n"),
1586 togglers[0]);
1587 if(possible&PUBKEY_USAGE_ENC)
1588 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1589 togglers[2]);
1590 if(possible&PUBKEY_USAGE_AUTH)
1591 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1592 togglers[4]);
1594 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1595 tty_printf("\n");
1597 xfree(answer);
1598 answer = cpr_get("keygen.flags",_("Your selection? "));
1599 cpr_kill_prompt();
1601 if(strlen(answer)>1)
1602 tty_printf(_("Invalid selection.\n"));
1603 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1604 break;
1605 else if((*answer==togglers[0] || *answer==togglers[1])
1606 && possible&PUBKEY_USAGE_SIG)
1608 if(current&PUBKEY_USAGE_SIG)
1609 current&=~PUBKEY_USAGE_SIG;
1610 else
1611 current|=PUBKEY_USAGE_SIG;
1613 else if((*answer==togglers[2] || *answer==togglers[3])
1614 && possible&PUBKEY_USAGE_ENC)
1616 if(current&PUBKEY_USAGE_ENC)
1617 current&=~PUBKEY_USAGE_ENC;
1618 else
1619 current|=PUBKEY_USAGE_ENC;
1621 else if((*answer==togglers[4] || *answer==togglers[5])
1622 && possible&PUBKEY_USAGE_AUTH)
1624 if(current&PUBKEY_USAGE_AUTH)
1625 current&=~PUBKEY_USAGE_AUTH;
1626 else
1627 current|=PUBKEY_USAGE_AUTH;
1629 else
1630 tty_printf(_("Invalid selection.\n"));
1633 xfree(answer);
1635 return current;
1639 /****************
1640 * Returns: 0 to create both a DSA and a Elgamal key.
1641 * and only if key flags are to be written the desired usage.
1643 static int
1644 ask_algo (int addmode, unsigned int *r_usage)
1646 char *answer;
1647 int algo;
1649 *r_usage = 0;
1650 tty_printf(_("Please select what kind of key you want:\n"));
1651 if( !addmode )
1652 tty_printf(_(" (%d) DSA and Elgamal (default)\n"), 1 );
1653 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
1654 if (opt.expert)
1655 tty_printf( _(" (%d) DSA (set your own capabilities)\n"), 3 );
1656 if( addmode )
1657 tty_printf(_(" (%d) Elgamal (encrypt only)\n"), 4 );
1658 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
1659 if (addmode)
1660 tty_printf(_(" (%d) RSA (encrypt only)\n"), 6 );
1661 if (opt.expert)
1662 tty_printf( _(" (%d) RSA (set your own capabilities)\n"), 7 );
1664 for(;;) {
1665 answer = cpr_get("keygen.algo",_("Your selection? "));
1666 cpr_kill_prompt();
1667 algo = *answer? atoi(answer): 1;
1668 xfree(answer);
1669 if( algo == 1 && !addmode ) {
1670 algo = 0; /* create both keys */
1671 break;
1673 else if( algo == 7 && opt.expert ) {
1674 algo = PUBKEY_ALGO_RSA;
1675 *r_usage=ask_key_flags(algo,addmode);
1676 break;
1678 else if( algo == 6 && addmode ) {
1679 algo = PUBKEY_ALGO_RSA;
1680 *r_usage = PUBKEY_USAGE_ENC;
1681 break;
1683 else if( algo == 5 ) {
1684 algo = PUBKEY_ALGO_RSA;
1685 *r_usage = PUBKEY_USAGE_SIG;
1686 break;
1688 else if( algo == 4 && addmode ) {
1689 algo = PUBKEY_ALGO_ELGAMAL_E;
1690 *r_usage = PUBKEY_USAGE_ENC;
1691 break;
1693 else if( algo == 3 && opt.expert ) {
1694 algo = PUBKEY_ALGO_DSA;
1695 *r_usage=ask_key_flags(algo,addmode);
1696 break;
1698 else if( algo == 2 ) {
1699 algo = PUBKEY_ALGO_DSA;
1700 *r_usage = PUBKEY_USAGE_SIG;
1701 break;
1703 else
1704 tty_printf(_("Invalid selection.\n"));
1707 return algo;
1711 static unsigned
1712 ask_keysize( int algo )
1714 unsigned int nbits, min, def=2048, max=4096;
1716 if(opt.expert)
1717 min=512;
1718 else
1719 min=1024;
1721 switch(algo)
1723 case PUBKEY_ALGO_DSA:
1724 if(opt.flags.dsa2)
1726 def=1024;
1727 max=3072;
1729 else
1731 tty_printf(_("DSA keypair will have %u bits.\n"),1024);
1732 return 1024;
1734 break;
1736 case PUBKEY_ALGO_RSA:
1737 min=1024;
1738 break;
1741 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1742 gcry_pk_algo_name (algo), min, max);
1744 for(;;)
1746 char *prompt,*answer;
1748 #define PROMPTSTRING _("What keysize do you want? (%u) ")
1750 prompt=xmalloc(strlen(PROMPTSTRING)+20);
1751 sprintf(prompt,PROMPTSTRING,def);
1753 #undef PROMPTSTRING
1755 answer = cpr_get("keygen.size",prompt);
1756 cpr_kill_prompt();
1757 nbits = *answer? atoi(answer): def;
1758 xfree(prompt);
1759 xfree(answer);
1761 if(nbits<min || nbits>max)
1762 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1763 gcry_pk_algo_name (algo), min, max);
1764 else
1765 break;
1768 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1770 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
1772 nbits = ((nbits + 63) / 64) * 64;
1773 tty_printf(_("rounded up to %u bits\n"), nbits );
1775 else if( (nbits % 32) )
1777 nbits = ((nbits + 31) / 32) * 32;
1778 tty_printf(_("rounded up to %u bits\n"), nbits );
1781 return nbits;
1785 /****************
1786 * Parse an expire string and return its value in seconds.
1787 * Returns (u32)-1 on error.
1788 * This isn't perfect since scan_isodatestr returns unix time, and
1789 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1790 * Because of this, we only permit setting expirations up to 2106, but
1791 * OpenPGP could theoretically allow up to 2242. I think we'll all
1792 * just cope for the next few years until we get a 64-bit time_t or
1793 * similar.
1796 parse_expire_string( const char *string )
1798 int mult;
1799 u32 seconds;
1800 u32 abs_date = 0;
1801 u32 curtime = make_timestamp ();
1803 if (!*string)
1804 seconds = 0;
1805 else if (!strncmp (string, "seconds=", 8))
1806 seconds = atoi (string+8);
1807 else if ((abs_date = scan_isodatestr(string)) && abs_date > curtime)
1808 seconds = abs_date - curtime;
1809 else if ((mult = check_valid_days (string)))
1810 seconds = atoi (string) * 86400L * mult;
1811 else
1812 seconds = (u32)(-1);
1814 return seconds;
1817 /* Parsean Creation-Date string which is either "1986-04-26" or
1818 "19860426T042640". Returns 0 on error. */
1819 static u32
1820 parse_creation_string (const char *string)
1822 u32 seconds;
1824 if (!*string)
1825 seconds = 0;
1826 else if ( !strncmp (string, "seconds=", 8) )
1827 seconds = atoi (string+8);
1828 else if ( !(seconds = scan_isodatestr (string)))
1830 time_t tmp = isotime2epoch (string);
1831 seconds = (tmp == (time_t)(-1))? 0 : tmp;
1833 return seconds;
1837 /* object == 0 for a key, and 1 for a sig */
1839 ask_expire_interval(int object,const char *def_expire)
1841 u32 interval;
1842 char *answer;
1844 switch(object)
1846 case 0:
1847 if(def_expire)
1848 BUG();
1849 tty_printf(_("Please specify how long the key should be valid.\n"
1850 " 0 = key does not expire\n"
1851 " <n> = key expires in n days\n"
1852 " <n>w = key expires in n weeks\n"
1853 " <n>m = key expires in n months\n"
1854 " <n>y = key expires in n years\n"));
1855 break;
1857 case 1:
1858 if(!def_expire)
1859 BUG();
1860 tty_printf(_("Please specify how long the signature should be valid.\n"
1861 " 0 = signature does not expire\n"
1862 " <n> = signature expires in n days\n"
1863 " <n>w = signature expires in n weeks\n"
1864 " <n>m = signature expires in n months\n"
1865 " <n>y = signature expires in n years\n"));
1866 break;
1868 default:
1869 BUG();
1872 /* Note: The elgamal subkey for DSA has no expiration date because
1873 * it must be signed with the DSA key and this one has the expiration
1874 * date */
1876 answer = NULL;
1877 for(;;)
1879 u32 curtime=make_timestamp();
1881 xfree(answer);
1882 if(object==0)
1883 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1884 else
1886 char *prompt;
1888 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1889 /* This will actually end up larger than necessary because
1890 of the 2 bytes for '%s' */
1891 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
1892 sprintf(prompt,PROMPTSTRING,def_expire);
1893 #undef PROMPTSTRING
1895 answer = cpr_get("siggen.valid",prompt);
1896 xfree(prompt);
1898 if(*answer=='\0')
1899 answer=xstrdup(def_expire);
1901 cpr_kill_prompt();
1902 trim_spaces(answer);
1903 interval = parse_expire_string( answer );
1904 if( interval == (u32)-1 )
1906 tty_printf(_("invalid value\n"));
1907 continue;
1910 if( !interval )
1912 tty_printf((object==0)
1913 ? _("Key does not expire at all\n")
1914 : _("Signature does not expire at all\n"));
1916 else
1918 tty_printf(object==0
1919 ? _("Key expires at %s\n")
1920 : _("Signature expires at %s\n"),
1921 asctimestamp((ulong)(curtime + interval) ) );
1922 #if SIZEOF_TIME_T <= 4
1923 if ( (time_t)((ulong)(curtime+interval)) < 0 )
1924 tty_printf (_("Your system can't display dates beyond 2038.\n"
1925 "However, it will be correctly handled up to"
1926 " 2106.\n"));
1927 else
1928 #endif /*SIZEOF_TIME_T*/
1929 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
1931 tty_printf (_("invalid value\n"));
1932 continue;
1936 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1937 _("Is this correct? (y/N) ")) )
1938 break;
1941 xfree(answer);
1942 return interval;
1946 ask_expiredate()
1948 u32 x = ask_expire_interval(0,NULL);
1949 return x? make_timestamp() + x : 0;
1953 static char *
1954 ask_user_id( int mode )
1956 char *answer;
1957 char *aname, *acomment, *amail, *uid;
1959 if ( !mode )
1961 /* TRANSLATORS: This is the new string telling the user what
1962 gpg is now going to do (i.e. ask for the parts of the user
1963 ID). Note that if you do not tyranslated this string, a
1964 different string will be used used, which might still have
1965 a correct transaltion. */
1966 const char *s1 =
1967 N_("\n"
1968 "GnuPG needs to construct a user ID to identify your key.\n"
1969 "\n");
1970 const char *s2 = _(s1);
1972 if (!strcmp (s1, s2))
1974 /* There is no translation for the string thus we to use
1975 the old info text. gettext has no way to tell whether
1976 a translation is actually available, thus we need to
1977 to compare again. */
1978 /* TRANSLATORS: This string is in general not anymore used
1979 but you should keep your existing translation. In case
1980 the new string is not translated this old string will
1981 be used. */
1982 const char *s3 = N_("\n"
1983 "You need a user ID to identify your key; "
1984 "the software constructs the user ID\n"
1985 "from the Real Name, Comment and Email Address in this form:\n"
1986 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
1987 const char *s4 = _(s3);
1988 if (strcmp (s3, s4))
1989 s2 = s3; /* A translation exists - use it. */
1991 tty_printf ("%s", s2) ;
1993 uid = aname = acomment = amail = NULL;
1994 for(;;) {
1995 char *p;
1996 int fail=0;
1998 if( !aname ) {
1999 for(;;) {
2000 xfree(aname);
2001 aname = cpr_get("keygen.name",_("Real name: "));
2002 trim_spaces(aname);
2003 cpr_kill_prompt();
2005 if( opt.allow_freeform_uid )
2006 break;
2008 if( strpbrk( aname, "<>" ) )
2009 tty_printf(_("Invalid character in name\n"));
2010 else if( digitp(aname) )
2011 tty_printf(_("Name may not start with a digit\n"));
2012 else if( strlen(aname) < 5 )
2013 tty_printf(_("Name must be at least 5 characters long\n"));
2014 else
2015 break;
2018 if( !amail ) {
2019 for(;;) {
2020 xfree(amail);
2021 amail = cpr_get("keygen.email",_("Email address: "));
2022 trim_spaces(amail);
2023 cpr_kill_prompt();
2024 if( !*amail || opt.allow_freeform_uid )
2025 break; /* no email address is okay */
2026 else if ( !is_valid_mailbox (amail) )
2027 tty_printf(_("Not a valid email address\n"));
2028 else
2029 break;
2032 if( !acomment ) {
2033 for(;;) {
2034 xfree(acomment);
2035 acomment = cpr_get("keygen.comment",_("Comment: "));
2036 trim_spaces(acomment);
2037 cpr_kill_prompt();
2038 if( !*acomment )
2039 break; /* no comment is okay */
2040 else if( strpbrk( acomment, "()" ) )
2041 tty_printf(_("Invalid character in comment\n"));
2042 else
2043 break;
2048 xfree(uid);
2049 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2050 p = stpcpy(p, aname );
2051 if( *acomment )
2052 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2053 if( *amail )
2054 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2056 /* Append a warning if the RNG is switched into fake mode. */
2057 if ( random_is_faked () )
2058 strcpy(p, " (insecure!)" );
2060 /* print a note in case that UTF8 mapping has to be done */
2061 for(p=uid; *p; p++ ) {
2062 if( *p & 0x80 ) {
2063 tty_printf(_("You are using the `%s' character set.\n"),
2064 get_native_charset() );
2065 break;
2069 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2070 /* fixme: add a warning if this user-id already exists */
2071 if( !*amail && !opt.allow_freeform_uid
2072 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2073 fail = 1;
2074 tty_printf(_("Please don't put the email address "
2075 "into the real name or the comment\n") );
2078 for(;;) {
2079 /* TRANSLATORS: These are the allowed answers in
2080 lower and uppercase. Below you will find the matching
2081 string which should be translated accordingly and the
2082 letter changed to match the one in the answer string.
2084 n = Change name
2085 c = Change comment
2086 e = Change email
2087 o = Okay (ready, continue)
2088 q = Quit
2090 const char *ansstr = _("NnCcEeOoQq");
2092 if( strlen(ansstr) != 10 )
2093 BUG();
2094 if( cpr_enabled() ) {
2095 answer = xstrdup(ansstr+6);
2096 answer[1] = 0;
2098 else {
2099 answer = cpr_get("keygen.userid.cmd", fail?
2100 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2101 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2102 cpr_kill_prompt();
2104 if( strlen(answer) > 1 )
2106 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2107 xfree(aname); aname = NULL;
2108 break;
2110 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2111 xfree(acomment); acomment = NULL;
2112 break;
2114 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2115 xfree(amail); amail = NULL;
2116 break;
2118 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2119 if( fail ) {
2120 tty_printf(_("Please correct the error first\n"));
2122 else {
2123 xfree(aname); aname = NULL;
2124 xfree(acomment); acomment = NULL;
2125 xfree(amail); amail = NULL;
2126 break;
2129 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2130 xfree(aname); aname = NULL;
2131 xfree(acomment); acomment = NULL;
2132 xfree(amail); amail = NULL;
2133 xfree(uid); uid = NULL;
2134 break;
2136 xfree(answer);
2138 xfree(answer);
2139 if( !amail && !acomment && !amail )
2140 break;
2141 xfree(uid); uid = NULL;
2143 if( uid ) {
2144 char *p = native_to_utf8( uid );
2145 xfree( uid );
2146 uid = p;
2148 return uid;
2152 static DEK *
2153 do_ask_passphrase ( STRING2KEY **ret_s2k, int *r_canceled )
2155 DEK *dek = NULL;
2156 STRING2KEY *s2k;
2157 const char *errtext = NULL;
2159 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2161 s2k = xmalloc_secure( sizeof *s2k );
2162 for(;;) {
2163 s2k->mode = opt.s2k_mode;
2164 s2k->hash_algo = S2K_DIGEST_ALGO;
2165 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k,2,
2166 errtext, r_canceled);
2167 if (!dek && *r_canceled) {
2168 xfree(dek); dek = NULL;
2169 xfree(s2k); s2k = NULL;
2170 break;
2172 else if( !dek ) {
2173 errtext = N_("passphrase not correctly repeated; try again");
2174 tty_printf(_("%s.\n"), _(errtext));
2176 else if( !dek->keylen ) {
2177 xfree(dek); dek = NULL;
2178 xfree(s2k); s2k = NULL;
2179 tty_printf(_(
2180 "You don't want a passphrase - this is probably a *bad* idea!\n"
2181 "I will do it anyway. You can change your passphrase at any time,\n"
2182 "using this program with the option \"--edit-key\".\n\n"));
2183 break;
2185 else
2186 break; /* okay */
2188 *ret_s2k = s2k;
2189 return dek;
2193 /* Basic key generation. Here we divert to the actual generation
2194 routines based on the requested algorithm. */
2195 static int
2196 do_create (int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
2197 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk,
2198 u32 timestamp, u32 expiredate, int is_subkey )
2200 int rc=0;
2202 if( !opt.batch )
2203 tty_printf(_(
2204 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2205 "some other action (type on the keyboard, move the mouse, utilize the\n"
2206 "disks) during the prime generation; this gives the random number\n"
2207 "generator a better chance to gain enough entropy.\n") );
2209 if( algo == PUBKEY_ALGO_ELGAMAL_E )
2210 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2211 timestamp, expiredate, is_subkey);
2212 else if( algo == PUBKEY_ALGO_DSA )
2213 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk,
2214 timestamp, expiredate, is_subkey);
2215 else if( algo == PUBKEY_ALGO_RSA )
2216 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2217 timestamp, expiredate, is_subkey);
2218 else
2219 BUG();
2221 return rc;
2225 /****************
2226 * Generate a new user id packet, or return NULL if canceled
2228 PKT_user_id *
2229 generate_user_id()
2231 PKT_user_id *uid;
2232 char *p;
2233 size_t n;
2235 p = ask_user_id( 1 );
2236 if( !p )
2237 return NULL;
2238 n = strlen(p);
2239 uid = xmalloc_clear( sizeof *uid + n );
2240 uid->len = n;
2241 strcpy(uid->name, p);
2242 uid->ref = 1;
2243 return uid;
2247 static void
2248 release_parameter_list( struct para_data_s *r )
2250 struct para_data_s *r2;
2252 for( ; r ; r = r2 ) {
2253 r2 = r->next;
2254 if( r->key == pPASSPHRASE_DEK )
2255 xfree( r->u.dek );
2256 else if( r->key == pPASSPHRASE_S2K )
2257 xfree( r->u.s2k );
2259 xfree(r);
2263 static struct para_data_s *
2264 get_parameter( struct para_data_s *para, enum para_name key )
2266 struct para_data_s *r;
2268 for( r = para; r && r->key != key; r = r->next )
2270 return r;
2273 static const char *
2274 get_parameter_value( struct para_data_s *para, enum para_name key )
2276 struct para_data_s *r = get_parameter( para, key );
2277 return (r && *r->u.value)? r->u.value : NULL;
2280 static int
2281 get_parameter_algo( struct para_data_s *para, enum para_name key )
2283 int i;
2284 struct para_data_s *r = get_parameter( para, key );
2285 if( !r )
2286 return -1;
2287 if( digitp( r->u.value ) )
2288 i = atoi( r->u.value );
2289 else if ( !strcmp ( r->u.value, "ELG-E")
2290 || !strcmp ( r->u.value, "ELG") )
2291 i = GCRY_PK_ELG_E;
2292 else
2293 i = gcry_pk_map_name (r->u.value);
2294 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2295 i = 0; /* we don't want to allow generation of these algorithms */
2296 return i;
2300 * Parse the usage parameter and set the keyflags. Returns -1 on
2301 * error, 0 for no usage given or 1 for usage available.
2303 static int
2304 parse_parameter_usage (const char *fname,
2305 struct para_data_s *para, enum para_name key)
2307 struct para_data_s *r = get_parameter( para, key );
2308 char *p, *pn;
2309 unsigned int use;
2311 if( !r )
2312 return 0; /* none (this is an optional parameter)*/
2314 use = 0;
2315 pn = r->u.value;
2316 while ( (p = strsep (&pn, " \t,")) ) {
2317 if ( !*p)
2319 else if ( !ascii_strcasecmp (p, "sign") )
2320 use |= PUBKEY_USAGE_SIG;
2321 else if ( !ascii_strcasecmp (p, "encrypt") )
2322 use |= PUBKEY_USAGE_ENC;
2323 else if ( !ascii_strcasecmp (p, "auth") )
2324 use |= PUBKEY_USAGE_AUTH;
2325 else {
2326 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2327 return -1; /* error */
2330 r->u.usage = use;
2331 return 1;
2334 static int
2335 parse_revocation_key (const char *fname,
2336 struct para_data_s *para, enum para_name key)
2338 struct para_data_s *r = get_parameter( para, key );
2339 struct revocation_key revkey;
2340 char *pn;
2341 int i;
2343 if( !r )
2344 return 0; /* none (this is an optional parameter) */
2346 pn = r->u.value;
2348 revkey.class=0x80;
2349 revkey.algid=atoi(pn);
2350 if(!revkey.algid)
2351 goto fail;
2353 /* Skip to the fpr */
2354 while(*pn && *pn!=':')
2355 pn++;
2357 if(*pn!=':')
2358 goto fail;
2360 pn++;
2362 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2364 int c=hextobyte(pn);
2365 if(c==-1)
2366 goto fail;
2368 revkey.fpr[i]=c;
2371 /* skip to the tag */
2372 while(*pn && *pn!='s' && *pn!='S')
2373 pn++;
2375 if(ascii_strcasecmp(pn,"sensitive")==0)
2376 revkey.class|=0x40;
2378 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2380 return 0;
2382 fail:
2383 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2384 return -1; /* error */
2388 static u32
2389 get_parameter_u32( struct para_data_s *para, enum para_name key )
2391 struct para_data_s *r = get_parameter( para, key );
2393 if( !r )
2394 return 0;
2395 if( r->key == pKEYCREATIONDATE )
2396 return r->u.creation;
2397 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2398 return r->u.expire;
2399 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2400 return r->u.usage;
2402 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2405 static unsigned int
2406 get_parameter_uint( struct para_data_s *para, enum para_name key )
2408 return get_parameter_u32( para, key );
2411 static DEK *
2412 get_parameter_dek( struct para_data_s *para, enum para_name key )
2414 struct para_data_s *r = get_parameter( para, key );
2415 return r? r->u.dek : NULL;
2418 static STRING2KEY *
2419 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2421 struct para_data_s *r = get_parameter( para, key );
2422 return r? r->u.s2k : NULL;
2425 static struct revocation_key *
2426 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2428 struct para_data_s *r = get_parameter( para, key );
2429 return r? &r->u.revkey : NULL;
2432 static int
2433 proc_parameter_file( struct para_data_s *para, const char *fname,
2434 struct output_control_s *outctrl, int card )
2436 struct para_data_s *r;
2437 const char *s1, *s2, *s3;
2438 size_t n;
2439 char *p;
2440 int have_user_id=0,err,algo;
2442 /* Check that we have all required parameters. */
2443 r = get_parameter( para, pKEYTYPE );
2444 if(r)
2446 algo=get_parameter_algo(para,pKEYTYPE);
2447 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2449 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2450 return -1;
2453 else
2455 log_error ("%s: no Key-Type specified\n",fname);
2456 return -1;
2459 err = parse_parameter_usage (fname, para, pKEYUSAGE);
2460 if (!err)
2462 /* Default to algo capabilities if key-usage is not provided */
2463 r = xmalloc_clear(sizeof(*r));
2464 r->key = pKEYUSAGE;
2465 r->u.usage = openpgp_pk_algo_usage(algo);
2466 r->next = para;
2467 para = r;
2469 else if (err == -1)
2470 return -1;
2471 else
2473 r = get_parameter (para, pKEYUSAGE);
2474 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2476 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2477 fname, r->lnr, algo);
2478 return -1;
2482 r = get_parameter( para, pSUBKEYTYPE );
2483 if(r)
2485 algo = get_parameter_algo (para, pSUBKEYTYPE);
2486 if (openpgp_pk_test_algo (algo))
2488 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2489 return -1;
2492 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2493 if (!err)
2495 /* Default to algo capabilities if subkey-usage is not
2496 provided */
2497 r = xmalloc_clear (sizeof(*r));
2498 r->key = pSUBKEYUSAGE;
2499 r->u.usage = openpgp_pk_algo_usage (algo);
2500 r->next = para;
2501 para = r;
2503 else if (err == -1)
2504 return -1;
2505 else
2507 r = get_parameter (para, pSUBKEYUSAGE);
2508 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2510 log_error ("%s:%d: specified Subkey-Usage not allowed"
2511 " for algo %d\n", fname, r->lnr, algo);
2512 return -1;
2518 if( get_parameter_value( para, pUSERID ) )
2519 have_user_id=1;
2520 else
2522 /* create the formatted user ID */
2523 s1 = get_parameter_value( para, pNAMEREAL );
2524 s2 = get_parameter_value( para, pNAMECOMMENT );
2525 s3 = get_parameter_value( para, pNAMEEMAIL );
2526 if( s1 || s2 || s3 )
2528 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2529 r = xmalloc_clear( sizeof *r + n + 20 );
2530 r->key = pUSERID;
2531 p = r->u.value;
2532 if( s1 )
2533 p = stpcpy(p, s1 );
2534 if( s2 )
2535 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2536 if( s3 )
2537 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2538 r->next = para;
2539 para = r;
2540 have_user_id=1;
2544 if(!have_user_id)
2546 log_error("%s: no User-ID specified\n",fname);
2547 return -1;
2550 /* Set preferences, if any. */
2551 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2553 /* Set keyserver, if any. */
2554 s1=get_parameter_value( para, pKEYSERVER );
2555 if(s1)
2557 struct keyserver_spec *spec;
2559 spec=parse_keyserver_uri(s1,1,NULL,0);
2560 if(spec)
2562 free_keyserver_spec(spec);
2563 opt.def_keyserver_url=s1;
2565 else
2567 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2568 return -1;
2572 /* Set revoker, if any. */
2573 if (parse_revocation_key (fname, para, pREVOKER))
2574 return -1;
2576 /* Make DEK and S2K from the Passphrase. */
2577 if (outctrl->ask_passphrase)
2579 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2580 feature is required so that GUIs are able to do a key
2581 creation but have gpg-agent ask for the passphrase. */
2582 int canceled = 0;
2583 STRING2KEY *s2k;
2584 DEK *dek;
2586 dek = do_ask_passphrase ( &s2k, &canceled );
2587 if (dek)
2589 r = xmalloc_clear( sizeof *r );
2590 r->key = pPASSPHRASE_DEK;
2591 r->u.dek = dek;
2592 r->next = para;
2593 para = r;
2594 r = xmalloc_clear( sizeof *r );
2595 r->key = pPASSPHRASE_S2K;
2596 r->u.s2k = s2k;
2597 r->next = para;
2598 para = r;
2601 if (canceled)
2603 log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
2604 return -1;
2607 else
2609 r = get_parameter( para, pPASSPHRASE );
2610 if ( r && *r->u.value )
2612 /* We have a plain text passphrase - create a DEK from it.
2613 * It is a little bit ridiculous to keep it in secure memory
2614 * but because we do this always, why not here. */
2615 STRING2KEY *s2k;
2616 DEK *dek;
2618 s2k = xmalloc_secure ( sizeof *s2k );
2619 s2k->mode = opt.s2k_mode;
2620 s2k->hash_algo = S2K_DIGEST_ALGO;
2621 set_next_passphrase ( r->u.value );
2622 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2623 NULL, NULL);
2624 set_next_passphrase (NULL );
2625 assert (dek);
2626 memset (r->u.value, 0, strlen(r->u.value));
2628 r = xmalloc_clear (sizeof *r);
2629 r->key = pPASSPHRASE_S2K;
2630 r->u.s2k = s2k;
2631 r->next = para;
2632 para = r;
2633 r = xmalloc_clear (sizeof *r);
2634 r->key = pPASSPHRASE_DEK;
2635 r->u.dek = dek;
2636 r->next = para;
2637 para = r;
2641 /* Make KEYCREATIONDATE from Creation-Date. */
2642 r = get_parameter (para, pCREATIONDATE);
2643 if (r && *r->u.value)
2645 u32 seconds;
2647 seconds = parse_creation_string (r->u.value);
2648 if (!seconds)
2650 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2651 return -1;
2653 r->u.creation = seconds;
2654 r->key = pKEYCREATIONDATE; /* Change that entry. */
2657 /* Make KEYEXPIRE from Expire-Date. */
2658 r = get_parameter( para, pEXPIREDATE );
2659 if( r && *r->u.value )
2661 u32 seconds;
2663 seconds = parse_expire_string( r->u.value );
2664 if( seconds == (u32)-1 )
2666 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2667 return -1;
2669 r->u.expire = seconds;
2670 r->key = pKEYEXPIRE; /* change hat entry */
2671 /* also set it for the subkey */
2672 r = xmalloc_clear( sizeof *r + 20 );
2673 r->key = pSUBKEYEXPIRE;
2674 r->u.expire = seconds;
2675 r->next = para;
2676 para = r;
2679 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2680 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2681 return -1;
2684 do_generate_keypair( para, outctrl, card );
2685 return 0;
2689 /****************
2690 * Kludge to allow non interactive key generation controlled
2691 * by a parameter file.
2692 * Note, that string parameters are expected to be in UTF-8
2694 static void
2695 read_parameter_file( const char *fname )
2697 static struct { const char *name;
2698 enum para_name key;
2699 } keywords[] = {
2700 { "Key-Type", pKEYTYPE},
2701 { "Key-Length", pKEYLENGTH },
2702 { "Key-Usage", pKEYUSAGE },
2703 { "Subkey-Type", pSUBKEYTYPE },
2704 { "Subkey-Length", pSUBKEYLENGTH },
2705 { "Subkey-Usage", pSUBKEYUSAGE },
2706 { "Name-Real", pNAMEREAL },
2707 { "Name-Email", pNAMEEMAIL },
2708 { "Name-Comment", pNAMECOMMENT },
2709 { "Expire-Date", pEXPIREDATE },
2710 { "Creation-Date", pCREATIONDATE },
2711 { "Passphrase", pPASSPHRASE },
2712 { "Preferences", pPREFERENCES },
2713 { "Revoker", pREVOKER },
2714 { "Handle", pHANDLE },
2715 { "Keyserver", pKEYSERVER },
2716 { NULL, 0 }
2718 IOBUF fp;
2719 byte *line;
2720 unsigned int maxlen, nline;
2721 char *p;
2722 int lnr;
2723 const char *err = NULL;
2724 struct para_data_s *para, *r;
2725 int i;
2726 struct output_control_s outctrl;
2728 memset( &outctrl, 0, sizeof( outctrl ) );
2729 outctrl.pub.afx = new_armor_context ();
2730 outctrl.sec.afx = new_armor_context ();
2732 if( !fname || !*fname)
2733 fname = "-";
2735 fp = iobuf_open (fname);
2736 if (fp && is_secured_file (iobuf_get_fd (fp)))
2738 iobuf_close (fp);
2739 fp = NULL;
2740 errno = EPERM;
2742 if (!fp) {
2743 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2744 return;
2746 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2748 lnr = 0;
2749 err = NULL;
2750 para = NULL;
2751 maxlen = 1024;
2752 line = NULL;
2753 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2754 char *keyword, *value;
2756 lnr++;
2757 if( !maxlen ) {
2758 err = "line too long";
2759 break;
2761 for( p = line; isspace(*(byte*)p); p++ )
2763 if( !*p || *p == '#' )
2764 continue;
2765 keyword = p;
2766 if( *keyword == '%' ) {
2767 for( ; !isspace(*(byte*)p); p++ )
2769 if( *p )
2770 *p++ = 0;
2771 for( ; isspace(*(byte*)p); p++ )
2773 value = p;
2774 trim_trailing_ws( value, strlen(value) );
2775 if( !ascii_strcasecmp( keyword, "%echo" ) )
2776 log_info("%s\n", value );
2777 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2778 outctrl.dryrun = 1;
2779 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
2780 outctrl.ask_passphrase = 1;
2781 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
2782 outctrl.ask_passphrase = 0;
2783 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2784 outctrl.lnr = lnr;
2785 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2786 print_status_key_not_created
2787 (get_parameter_value (para, pHANDLE));
2788 release_parameter_list( para );
2789 para = NULL;
2791 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2792 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2793 ; /* still the same file - ignore it */
2794 else {
2795 xfree( outctrl.pub.newfname );
2796 outctrl.pub.newfname = xstrdup( value );
2797 outctrl.use_files = 1;
2800 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2801 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2802 ; /* still the same file - ignore it */
2803 else {
2804 xfree( outctrl.sec.newfname );
2805 outctrl.sec.newfname = xstrdup( value );
2806 outctrl.use_files = 1;
2809 else
2810 log_info("skipping control `%s' (%s)\n", keyword, value );
2813 continue;
2817 if( !(p = strchr( p, ':' )) || p == keyword ) {
2818 err = "missing colon";
2819 break;
2821 if( *p )
2822 *p++ = 0;
2823 for( ; isspace(*(byte*)p); p++ )
2825 if( !*p ) {
2826 err = "missing argument";
2827 break;
2829 value = p;
2830 trim_trailing_ws( value, strlen(value) );
2832 for(i=0; keywords[i].name; i++ ) {
2833 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2834 break;
2836 if( !keywords[i].name ) {
2837 err = "unknown keyword";
2838 break;
2840 if( keywords[i].key != pKEYTYPE && !para ) {
2841 err = "parameter block does not start with \"Key-Type\"";
2842 break;
2845 if( keywords[i].key == pKEYTYPE && para ) {
2846 outctrl.lnr = lnr;
2847 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2848 print_status_key_not_created
2849 (get_parameter_value (para, pHANDLE));
2850 release_parameter_list( para );
2851 para = NULL;
2853 else {
2854 for( r = para; r; r = r->next ) {
2855 if( r->key == keywords[i].key )
2856 break;
2858 if( r ) {
2859 err = "duplicate keyword";
2860 break;
2863 r = xmalloc_clear( sizeof *r + strlen( value ) );
2864 r->lnr = lnr;
2865 r->key = keywords[i].key;
2866 strcpy( r->u.value, value );
2867 r->next = para;
2868 para = r;
2870 if( err )
2871 log_error("%s:%d: %s\n", fname, lnr, err );
2872 else if( iobuf_error (fp) ) {
2873 log_error("%s:%d: read error\n", fname, lnr);
2875 else if( para ) {
2876 outctrl.lnr = lnr;
2877 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2878 print_status_key_not_created (get_parameter_value (para, pHANDLE));
2881 if( outctrl.use_files ) { /* close open streams */
2882 iobuf_close( outctrl.pub.stream );
2883 iobuf_close( outctrl.sec.stream );
2885 /* Must invalidate that ugly cache to actually close it. */
2886 if (outctrl.pub.fname)
2887 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
2888 if (outctrl.sec.fname)
2889 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
2891 xfree( outctrl.pub.fname );
2892 xfree( outctrl.pub.newfname );
2893 xfree( outctrl.sec.fname );
2894 xfree( outctrl.sec.newfname );
2897 release_parameter_list( para );
2898 iobuf_close (fp);
2899 release_armor_context (outctrl.pub.afx);
2900 release_armor_context (outctrl.sec.afx);
2905 * Generate a keypair (fname is only used in batch mode) If
2906 * CARD_SERIALNO is not NULL the function will create the keys on an
2907 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2908 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2909 * generate in software, imported to the card and a backup file
2910 * written to directory given by this argument .
2912 void
2913 generate_keypair (const char *fname, const char *card_serialno,
2914 const char *backup_encryption_dir)
2916 unsigned int nbits;
2917 char *uid = NULL;
2918 DEK *dek;
2919 STRING2KEY *s2k;
2920 int algo;
2921 unsigned int use;
2922 int both = 0;
2923 u32 expire;
2924 struct para_data_s *para = NULL;
2925 struct para_data_s *r;
2926 struct output_control_s outctrl;
2927 int canceled;
2929 memset( &outctrl, 0, sizeof( outctrl ) );
2931 if (opt.batch && card_serialno)
2933 /* We don't yet support unattended key generation. */
2934 log_error (_("can't do this in batch mode\n"));
2935 return;
2938 if (opt.batch)
2940 read_parameter_file( fname );
2941 return;
2944 if (card_serialno)
2946 #ifdef ENABLE_CARD_SUPPORT
2947 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
2948 r->key = pSERIALNO;
2949 strcpy( r->u.value, card_serialno);
2950 r->next = para;
2951 para = r;
2953 algo = PUBKEY_ALGO_RSA;
2955 r = xcalloc (1, sizeof *r + 20 );
2956 r->key = pKEYTYPE;
2957 sprintf( r->u.value, "%d", algo );
2958 r->next = para;
2959 para = r;
2960 r = xcalloc (1, sizeof *r + 20 );
2961 r->key = pKEYUSAGE;
2962 strcpy (r->u.value, "sign");
2963 r->next = para;
2964 para = r;
2966 r = xcalloc (1, sizeof *r + 20 );
2967 r->key = pSUBKEYTYPE;
2968 sprintf( r->u.value, "%d", algo );
2969 r->next = para;
2970 para = r;
2971 r = xcalloc (1, sizeof *r + 20 );
2972 r->key = pSUBKEYUSAGE;
2973 strcpy (r->u.value, "encrypt");
2974 r->next = para;
2975 para = r;
2977 r = xcalloc (1, sizeof *r + 20 );
2978 r->key = pAUTHKEYTYPE;
2979 sprintf( r->u.value, "%d", algo );
2980 r->next = para;
2981 para = r;
2983 if (backup_encryption_dir)
2985 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
2986 r->key = pBACKUPENCDIR;
2987 strcpy (r->u.value, backup_encryption_dir);
2988 r->next = para;
2989 para = r;
2991 #endif /*ENABLE_CARD_SUPPORT*/
2993 else
2995 algo = ask_algo( 0, &use );
2996 if( !algo )
2997 { /* default: DSA with ElG subkey of the specified size */
2998 both = 1;
2999 r = xmalloc_clear( sizeof *r + 20 );
3000 r->key = pKEYTYPE;
3001 sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
3002 r->next = para;
3003 para = r;
3004 nbits = ask_keysize( PUBKEY_ALGO_DSA );
3005 r = xmalloc_clear( sizeof *r + 20 );
3006 r->key = pKEYLENGTH;
3007 sprintf( r->u.value, "%u", nbits);
3008 r->next = para;
3009 para = r;
3010 r = xmalloc_clear( sizeof *r + 20 );
3011 r->key = pKEYUSAGE;
3012 strcpy( r->u.value, "sign" );
3013 r->next = para;
3014 para = r;
3016 algo = PUBKEY_ALGO_ELGAMAL_E;
3017 r = xmalloc_clear( sizeof *r + 20 );
3018 r->key = pSUBKEYTYPE;
3019 sprintf( r->u.value, "%d", algo );
3020 r->next = para;
3021 para = r;
3022 r = xmalloc_clear( sizeof *r + 20 );
3023 r->key = pSUBKEYUSAGE;
3024 strcpy( r->u.value, "encrypt" );
3025 r->next = para;
3026 para = r;
3028 else
3030 r = xmalloc_clear( sizeof *r + 20 );
3031 r->key = pKEYTYPE;
3032 sprintf( r->u.value, "%d", algo );
3033 r->next = para;
3034 para = r;
3036 if (use)
3038 r = xmalloc_clear( sizeof *r + 25 );
3039 r->key = pKEYUSAGE;
3040 sprintf( r->u.value, "%s%s%s",
3041 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3042 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3043 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3044 r->next = para;
3045 para = r;
3050 nbits = ask_keysize( algo );
3051 r = xmalloc_clear( sizeof *r + 20 );
3052 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3053 sprintf( r->u.value, "%u", nbits);
3054 r->next = para;
3055 para = r;
3058 expire = ask_expire_interval(0,NULL);
3059 r = xmalloc_clear( sizeof *r + 20 );
3060 r->key = pKEYEXPIRE;
3061 r->u.expire = expire;
3062 r->next = para;
3063 para = r;
3064 r = xmalloc_clear( sizeof *r + 20 );
3065 r->key = pSUBKEYEXPIRE;
3066 r->u.expire = expire;
3067 r->next = para;
3068 para = r;
3070 uid = ask_user_id(0);
3071 if( !uid )
3073 log_error(_("Key generation canceled.\n"));
3074 release_parameter_list( para );
3075 return;
3077 r = xmalloc_clear( sizeof *r + strlen(uid) );
3078 r->key = pUSERID;
3079 strcpy( r->u.value, uid );
3080 r->next = para;
3081 para = r;
3083 canceled = 0;
3084 dek = card_serialno? NULL : do_ask_passphrase ( &s2k, &canceled );
3085 if( dek )
3087 r = xmalloc_clear( sizeof *r );
3088 r->key = pPASSPHRASE_DEK;
3089 r->u.dek = dek;
3090 r->next = para;
3091 para = r;
3092 r = xmalloc_clear( sizeof *r );
3093 r->key = pPASSPHRASE_S2K;
3094 r->u.s2k = s2k;
3095 r->next = para;
3096 para = r;
3099 if (canceled)
3100 log_error (_("Key generation canceled.\n"));
3101 else
3102 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3103 release_parameter_list( para );
3107 #ifdef ENABLE_CARD_SUPPORT
3108 /* Generate a raw key and return it as a secret key packet. The
3109 function will ask for the passphrase and return a protected as well
3110 as an unprotected copy of a new secret key packet. 0 is returned
3111 on success and the caller must then free the returned values. */
3112 static int
3113 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3114 PKT_secret_key **r_sk_unprotected,
3115 PKT_secret_key **r_sk_protected)
3117 int rc;
3118 DEK *dek = NULL;
3119 STRING2KEY *s2k = NULL;
3120 PKT_secret_key *sk = NULL;
3121 int i;
3122 size_t nskey, npkey;
3123 gcry_sexp_t s_parms, s_key;
3124 int canceled;
3126 npkey = pubkey_get_npkey (algo);
3127 nskey = pubkey_get_nskey (algo);
3128 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3130 if (nbits < 512)
3132 nbits = 512;
3133 log_info (_("keysize invalid; using %u bits\n"), nbits );
3136 if ((nbits % 32))
3138 nbits = ((nbits + 31) / 32) * 32;
3139 log_info(_("keysize rounded up to %u bits\n"), nbits );
3142 dek = do_ask_passphrase (&s2k, &canceled);
3143 if (canceled)
3145 rc = gpg_error (GPG_ERR_CANCELED);
3146 goto leave;
3149 sk = xmalloc_clear (sizeof *sk);
3150 sk->timestamp = created_at;
3151 sk->version = 4;
3152 sk->pubkey_algo = algo;
3154 if ( !is_RSA (algo) )
3156 log_error ("only RSA is supported for offline generated keys\n");
3157 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3158 goto leave;
3160 rc = gcry_sexp_build (&s_parms, NULL,
3161 "(genkey(rsa(nbits %d)))",
3162 (int)nbits);
3163 if (rc)
3164 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3165 rc = gcry_pk_genkey (&s_key, s_parms);
3166 gcry_sexp_release (s_parms);
3167 if (rc)
3169 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3170 goto leave;
3172 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3173 gcry_sexp_release (s_key);
3174 if (rc)
3176 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3177 goto leave;
3180 for (i=npkey; i < nskey; i++)
3181 sk->csum += checksum_mpi (sk->skey[i]);
3183 if (r_sk_unprotected)
3184 *r_sk_unprotected = copy_secret_key (NULL, sk);
3186 rc = genhelp_protect (dek, s2k, sk);
3187 if (rc)
3188 goto leave;
3190 if (r_sk_protected)
3192 *r_sk_protected = sk;
3193 sk = NULL;
3196 leave:
3197 if (sk)
3198 free_secret_key (sk);
3199 xfree (dek);
3200 xfree (s2k);
3201 return rc;
3203 #endif /* ENABLE_CARD_SUPPORT */
3205 /* Create and delete a dummy packet to start off a list of kbnodes. */
3206 static void
3207 start_tree(KBNODE *tree)
3209 PACKET *pkt;
3211 pkt=xmalloc_clear(sizeof(*pkt));
3212 pkt->pkttype=PKT_NONE;
3213 *tree=new_kbnode(pkt);
3214 delete_kbnode(*tree);
3218 static void
3219 do_generate_keypair (struct para_data_s *para,
3220 struct output_control_s *outctrl, int card)
3222 KBNODE pub_root = NULL;
3223 KBNODE sec_root = NULL;
3224 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3225 const char *s;
3226 struct revocation_key *revkey;
3227 int rc;
3228 int did_sub = 0;
3229 u32 timestamp;
3231 if( outctrl->dryrun )
3233 log_info("dry-run mode - key generation skipped\n");
3234 return;
3237 if ( outctrl->use_files )
3239 if ( outctrl->pub.newfname )
3241 iobuf_close(outctrl->pub.stream);
3242 outctrl->pub.stream = NULL;
3243 if (outctrl->pub.fname)
3244 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3245 xfree( outctrl->pub.fname );
3246 outctrl->pub.fname = outctrl->pub.newfname;
3247 outctrl->pub.newfname = NULL;
3249 if (is_secured_filename (outctrl->pub.fname) )
3251 outctrl->pub.stream = NULL;
3252 errno = EPERM;
3254 else
3255 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3256 if (!outctrl->pub.stream)
3258 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3259 strerror(errno) );
3260 return;
3262 if (opt.armor)
3264 outctrl->pub.afx->what = 1;
3265 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3268 if (outctrl->sec.newfname)
3270 mode_t oldmask;
3272 iobuf_close(outctrl->sec.stream);
3273 outctrl->sec.stream = NULL;
3274 if (outctrl->sec.fname)
3275 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3276 xfree( outctrl->sec.fname );
3277 outctrl->sec.fname = outctrl->sec.newfname;
3278 outctrl->sec.newfname = NULL;
3280 oldmask = umask (077);
3281 if (is_secured_filename (outctrl->sec.fname) )
3283 outctrl->sec.stream = NULL;
3284 errno = EPERM;
3286 else
3287 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3288 umask (oldmask);
3289 if (!outctrl->sec.stream)
3291 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3292 strerror(errno) );
3293 return;
3295 if (opt.armor)
3297 outctrl->sec.afx->what = 5;
3298 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3301 assert( outctrl->pub.stream );
3302 assert( outctrl->sec.stream );
3303 if (opt.verbose)
3305 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3306 if (card)
3307 log_info (_("writing secret key stub to `%s'\n"),
3308 outctrl->sec.fname);
3309 else
3310 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3315 /* We create the packets as a tree of kbnodes. Because the
3316 structure we create is known in advance we simply generate a
3317 linked list. The first packet is a dummy packet which we flag as
3318 deleted. The very first packet must always be a KEY packet. */
3320 start_tree (&pub_root);
3321 start_tree (&sec_root);
3323 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3324 if (!timestamp)
3325 timestamp = make_timestamp ();
3327 if (!card)
3329 rc = do_create (get_parameter_algo( para, pKEYTYPE ),
3330 get_parameter_uint( para, pKEYLENGTH ),
3331 pub_root, sec_root,
3332 get_parameter_dek( para, pPASSPHRASE_DEK ),
3333 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3334 &pri_sk,
3335 timestamp,
3336 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3338 else
3340 /* Note, that depending on the backend, the card key generation
3341 may update TIMESTAMP. */
3342 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3343 &timestamp,
3344 get_parameter_u32 (para, pKEYEXPIRE), para);
3345 if (!rc)
3347 pri_sk = sec_root->next->pkt->pkt.secret_key;
3348 assert (pri_sk);
3352 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3354 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3355 if (!rc)
3356 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3359 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3361 write_uid (pub_root, s );
3362 write_uid (sec_root, s );
3364 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3365 get_parameter_uint (para, pKEYUSAGE), timestamp);
3368 /* Write the auth key to the card before the encryption key. This
3369 is a partial workaround for a PGP bug (as of this writing, all
3370 versions including 8.1), that causes it to try and encrypt to
3371 the most recent subkey regardless of whether that subkey is
3372 actually an encryption type. In this case, the auth key is an
3373 RSA key so it succeeds. */
3375 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3377 /* Note, that depending on the backend, the card key generation
3378 may update TIMESTAMP. */
3379 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3380 &timestamp,
3381 get_parameter_u32 (para, pKEYEXPIRE), para);
3383 if (!rc)
3384 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3385 PUBKEY_USAGE_AUTH, timestamp);
3386 if (!rc)
3387 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3388 PUBKEY_USAGE_AUTH, timestamp);
3391 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3393 if (!card)
3395 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
3396 get_parameter_uint( para, pSUBKEYLENGTH ),
3397 pub_root, sec_root,
3398 get_parameter_dek( para, pPASSPHRASE_DEK ),
3399 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3400 &sub_sk,
3401 timestamp,
3402 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3404 else
3406 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3408 /* A backup of the encryption key has been requested.
3409 Generate the key in software and import it then to
3410 the card. Write a backup file. */
3411 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3412 pub_root, sec_root,
3413 timestamp,
3414 get_parameter_u32 (para,
3415 pKEYEXPIRE),
3416 para, s);
3418 else
3420 /* Note, that depending on the backend, the card key
3421 generation may update TIMESTAMP. */
3422 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3423 NULL,
3424 &timestamp,
3425 get_parameter_u32 (para, pKEYEXPIRE), para);
3429 if( !rc )
3430 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3431 get_parameter_uint (para, pSUBKEYUSAGE),
3432 timestamp);
3433 if( !rc )
3434 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3435 get_parameter_uint (para, pSUBKEYUSAGE),
3436 timestamp);
3437 did_sub = 1;
3440 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3442 rc = write_keyblock( outctrl->pub.stream, pub_root );
3443 if (rc)
3444 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3445 if (!rc)
3447 rc = write_keyblock( outctrl->sec.stream, sec_root );
3448 if(rc)
3449 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3452 else if (!rc) /* Write to the standard keyrings. */
3454 KEYDB_HANDLE pub_hd = keydb_new (0);
3455 KEYDB_HANDLE sec_hd = keydb_new (1);
3457 rc = keydb_locate_writable (pub_hd, NULL);
3458 if (rc)
3459 log_error (_("no writable public keyring found: %s\n"),
3460 g10_errstr (rc));
3462 if (!rc)
3464 rc = keydb_locate_writable (sec_hd, NULL);
3465 if (rc)
3466 log_error (_("no writable secret keyring found: %s\n"),
3467 g10_errstr (rc));
3470 if (!rc && opt.verbose)
3472 log_info (_("writing public key to `%s'\n"),
3473 keydb_get_resource_name (pub_hd));
3474 if (card)
3475 log_info (_("writing secret key stub to `%s'\n"),
3476 keydb_get_resource_name (sec_hd));
3477 else
3478 log_info (_("writing secret key to `%s'\n"),
3479 keydb_get_resource_name (sec_hd));
3482 if (!rc)
3484 rc = keydb_insert_keyblock (pub_hd, pub_root);
3485 if (rc)
3486 log_error (_("error writing public keyring `%s': %s\n"),
3487 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3490 if (!rc)
3492 rc = keydb_insert_keyblock (sec_hd, sec_root);
3493 if (rc)
3494 log_error (_("error writing secret keyring `%s': %s\n"),
3495 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3498 keydb_release (pub_hd);
3499 keydb_release (sec_hd);
3501 if (!rc)
3503 int no_enc_rsa;
3504 PKT_public_key *pk;
3506 no_enc_rsa = (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
3507 && get_parameter_uint (para, pKEYUSAGE)
3508 && !((get_parameter_uint (para, pKEYUSAGE)
3509 & PUBKEY_USAGE_ENC)) );
3511 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3513 keyid_from_pk(pk,pk->main_keyid);
3514 register_trusted_keyid(pk->main_keyid);
3516 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3517 | TRUST_ULTIMATE ));
3519 if (!opt.batch)
3521 tty_printf (_("public and secret key created and signed.\n") );
3522 tty_printf ("\n");
3523 list_keyblock(pub_root,0,1,NULL);
3527 if (!opt.batch
3528 && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
3529 || no_enc_rsa )
3530 && !get_parameter (para, pSUBKEYTYPE) )
3532 tty_printf(_("Note that this key cannot be used for "
3533 "encryption. You may want to use\n"
3534 "the command \"--edit-key\" to generate a "
3535 "subkey for this purpose.\n") );
3540 if (rc)
3542 if (opt.batch)
3543 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3544 else
3545 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3546 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3548 else
3550 PKT_public_key *pk = find_kbnode (pub_root,
3551 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3552 print_status_key_created (did_sub? 'B':'P', pk,
3553 get_parameter_value (para, pHANDLE));
3555 release_kbnode( pub_root );
3556 release_kbnode( sec_root );
3558 if (pri_sk && !card) /* The unprotected secret key unless we */
3559 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3560 if (sub_sk)
3561 free_secret_key(sub_sk);
3565 /* Add a new subkey to an existing key. Returns true if a new key has
3566 been generated and put into the keyblocks. */
3568 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3570 int okay=0, rc=0;
3571 KBNODE node;
3572 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3573 int algo;
3574 unsigned int use;
3575 u32 expire;
3576 unsigned nbits;
3577 char *passphrase = NULL;
3578 DEK *dek = NULL;
3579 STRING2KEY *s2k = NULL;
3580 u32 cur_time;
3581 int ask_pass = 0;
3582 int canceled;
3584 /* Break out the primary secret key. */
3585 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3586 if( !node )
3588 log_error ("Oops; secret key not found anymore!\n");
3589 goto leave;
3592 /* Make a copy of the sk to keep the protected one in the keyblock. */
3593 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3595 cur_time = make_timestamp();
3597 if (pri_sk->timestamp > cur_time)
3599 ulong d = pri_sk->timestamp - cur_time;
3600 log_info ( d==1 ? _("key has been created %lu second "
3601 "in future (time warp or clock problem)\n")
3602 : _("key has been created %lu seconds "
3603 "in future (time warp or clock problem)\n"), d );
3604 if (!opt.ignore_time_conflict)
3606 rc = G10ERR_TIME_CONFLICT;
3607 goto leave;
3611 if (pri_sk->version < 4)
3613 log_info (_("NOTE: creating subkeys for v3 keys "
3614 "is not OpenPGP compliant\n"));
3615 goto leave;
3618 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3620 tty_printf (_("Secret parts of primary key are not available.\n"));
3621 rc = G10ERR_NO_SECKEY;
3622 goto leave;
3626 /* Unprotect to get the passphrase. */
3627 switch (is_secret_key_protected (pri_sk) )
3629 case -1:
3630 rc = G10ERR_PUBKEY_ALGO;
3631 break;
3632 case 0:
3633 tty_printf (_("This key is not protected.\n"));
3634 break;
3635 case -2:
3636 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3637 ask_pass = 1;
3638 break;
3639 default:
3640 tty_printf (_("Key is protected.\n"));
3641 rc = check_secret_key ( pri_sk, 0 );
3642 if (!rc)
3643 passphrase = get_last_passphrase();
3644 break;
3646 if (rc)
3647 goto leave;
3649 algo = ask_algo (1, &use);
3650 assert (algo);
3651 nbits = ask_keysize (algo);
3652 expire = ask_expire_interval (0, NULL);
3653 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3654 _("Really create? (y/N) ")))
3655 goto leave;
3657 canceled = 0;
3658 if (ask_pass)
3659 dek = do_ask_passphrase (&s2k, &canceled);
3660 else if (passphrase)
3662 s2k = xmalloc_secure ( sizeof *s2k );
3663 s2k->mode = opt.s2k_mode;
3664 s2k->hash_algo = S2K_DIGEST_ALGO;
3665 set_next_passphrase ( passphrase );
3666 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3667 NULL, NULL );
3670 if (canceled)
3671 rc = GPG_ERR_CANCELED;
3673 if (!rc)
3674 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3675 dek, s2k, &sub_sk, cur_time, expire, 1 );
3676 if (!rc)
3677 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3678 use, cur_time);
3679 if (!rc)
3680 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3681 use, cur_time);
3682 if (!rc)
3684 okay = 1;
3685 write_status_text (STATUS_KEY_CREATED, "S");
3688 leave:
3689 if (rc)
3690 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3691 xfree (passphrase);
3692 xfree (dek);
3693 xfree (s2k);
3694 /* Release the copy of the (now unprotected) secret keys. */
3695 if (pri_sk)
3696 free_secret_key (pri_sk);
3697 if (sub_sk)
3698 free_secret_key (sub_sk);
3699 set_next_passphrase (NULL);
3700 return okay;
3704 #ifdef ENABLE_CARD_SUPPORT
3705 /* Generate a subkey on a card. */
3707 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3708 int keyno, const char *serialno)
3710 int okay=0, rc=0;
3711 KBNODE node;
3712 PKT_secret_key *pri_sk = NULL, *sub_sk;
3713 int algo;
3714 unsigned int use;
3715 u32 expire;
3716 char *passphrase = NULL;
3717 u32 cur_time;
3718 struct para_data_s *para = NULL;
3720 assert (keyno >= 1 && keyno <= 3);
3722 para = xcalloc (1, sizeof *para + strlen (serialno) );
3723 para->key = pSERIALNO;
3724 strcpy (para->u.value, serialno);
3726 /* Break out the primary secret key */
3727 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3728 if (!node)
3730 log_error("Oops; secret key not found anymore!\n");
3731 goto leave;
3734 /* Make a copy of the sk to keep the protected one in the keyblock */
3735 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3737 cur_time = make_timestamp();
3738 if (pri_sk->timestamp > cur_time)
3740 ulong d = pri_sk->timestamp - cur_time;
3741 log_info (d==1 ? _("key has been created %lu second "
3742 "in future (time warp or clock problem)\n")
3743 : _("key has been created %lu seconds "
3744 "in future (time warp or clock problem)\n"), d );
3745 if (!opt.ignore_time_conflict)
3747 rc = G10ERR_TIME_CONFLICT;
3748 goto leave;
3752 if (pri_sk->version < 4)
3754 log_info (_("NOTE: creating subkeys for v3 keys "
3755 "is not OpenPGP compliant\n"));
3756 goto leave;
3759 /* Unprotect to get the passphrase. */
3760 switch( is_secret_key_protected (pri_sk) )
3762 case -1:
3763 rc = G10ERR_PUBKEY_ALGO;
3764 break;
3765 case 0:
3766 tty_printf("This key is not protected.\n");
3767 break;
3768 default:
3769 tty_printf("Key is protected.\n");
3770 rc = check_secret_key( pri_sk, 0 );
3771 if (!rc)
3772 passphrase = get_last_passphrase();
3773 break;
3775 if (rc)
3776 goto leave;
3778 algo = PUBKEY_ALGO_RSA;
3779 expire = ask_expire_interval (0,NULL);
3780 if (keyno == 1)
3781 use = PUBKEY_USAGE_SIG;
3782 else if (keyno == 2)
3783 use = PUBKEY_USAGE_ENC;
3784 else
3785 use = PUBKEY_USAGE_AUTH;
3786 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3787 _("Really create? (y/N) ")))
3788 goto leave;
3790 if (passphrase)
3791 set_next_passphrase (passphrase);
3793 /* Note, that depending on the backend, the card key generation may
3794 update CUR_TIME. */
3795 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3796 &sub_sk, &cur_time, expire, para);
3797 if (!rc)
3798 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3799 use, cur_time);
3800 if (!rc)
3801 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3802 use, cur_time);
3803 if (!rc)
3805 okay = 1;
3806 write_status_text (STATUS_KEY_CREATED, "S");
3809 leave:
3810 if (rc)
3811 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3812 xfree (passphrase);
3813 /* Release the copy of the (now unprotected) secret keys. */
3814 if (pri_sk)
3815 free_secret_key (pri_sk);
3816 set_next_passphrase( NULL );
3817 release_parameter_list (para);
3818 return okay;
3820 #endif /* !ENABLE_CARD_SUPPORT */
3824 * Write a keyblock to an output stream
3826 static int
3827 write_keyblock( IOBUF out, KBNODE node )
3829 for( ; node ; node = node->next )
3831 if(!is_deleted_kbnode(node))
3833 int rc = build_packet( out, node->pkt );
3834 if( rc )
3836 log_error("build_packet(%d) failed: %s\n",
3837 node->pkt->pkttype, g10_errstr(rc) );
3838 return rc;
3843 return 0;
3847 /* Note that timestamp is an in/out arg. */
3848 static int
3849 gen_card_key (int algo, int keyno, int is_primary,
3850 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
3851 u32 *timestamp, u32 expireval, struct para_data_s *para)
3853 #ifdef ENABLE_CARD_SUPPORT
3854 int rc;
3855 const char *s;
3856 struct agent_card_genkey_s info;
3857 PACKET *pkt;
3858 PKT_secret_key *sk;
3859 PKT_public_key *pk;
3861 assert (algo == PUBKEY_ALGO_RSA);
3863 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3864 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
3865 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3866 /* { */
3867 /* tty_printf ("\n"); */
3868 /* log_error ("WARNING: key does already exists!\n"); */
3869 /* tty_printf ("\n"); */
3870 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3871 /* _("Replace existing key? "))) */
3872 /* rc = agent_scd_genkey (&info, keyno, 1); */
3873 /* } */
3875 if (rc)
3877 log_error ("key generation failed: %s\n", gpg_strerror (rc));
3878 return rc;
3880 if ( !info.n || !info.e )
3882 log_error ("communication error with SCD\n");
3883 gcry_mpi_release (info.n);
3884 gcry_mpi_release (info.e);
3885 return gpg_error (GPG_ERR_GENERAL);
3888 if (*timestamp != info.created_at)
3889 log_info ("Note that the key does not use the suggested creation date\n");
3890 *timestamp = info.created_at;
3892 pk = xcalloc (1, sizeof *pk );
3893 sk = xcalloc (1, sizeof *sk );
3894 sk->timestamp = pk->timestamp = info.created_at;
3895 sk->version = pk->version = 4;
3896 if (expireval)
3897 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
3898 sk->pubkey_algo = pk->pubkey_algo = algo;
3899 pk->pkey[0] = info.n;
3900 pk->pkey[1] = info.e;
3901 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
3902 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
3903 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3904 sk->is_protected = 1;
3905 sk->protect.s2k.mode = 1002;
3906 s = get_parameter_value (para, pSERIALNO);
3907 if (s)
3909 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3910 sk->protect.ivlen++, s += 2)
3911 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3914 if( ret_sk )
3915 *ret_sk = sk;
3917 pkt = xcalloc (1,sizeof *pkt);
3918 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
3919 pkt->pkt.public_key = pk;
3920 add_kbnode(pub_root, new_kbnode( pkt ));
3922 pkt = xcalloc (1,sizeof *pkt);
3923 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
3924 pkt->pkt.secret_key = sk;
3925 add_kbnode(sec_root, new_kbnode( pkt ));
3927 return 0;
3928 #else
3929 return -1;
3930 #endif /*!ENABLE_CARD_SUPPORT*/
3935 static int
3936 gen_card_key_with_backup (int algo, int keyno, int is_primary,
3937 KBNODE pub_root, KBNODE sec_root,
3938 u32 timestamp,
3939 u32 expireval, struct para_data_s *para,
3940 const char *backup_dir)
3942 #ifdef ENABLE_CARD_SUPPORT
3943 int rc;
3944 const char *s;
3945 PACKET *pkt;
3946 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
3947 PKT_public_key *pk;
3948 size_t n;
3949 int i;
3951 rc = generate_raw_key (algo, 1024, timestamp,
3952 &sk_unprotected, &sk_protected);
3953 if (rc)
3954 return rc;
3956 /* First, store the key to the card. */
3957 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
3958 if (rc)
3960 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
3961 free_secret_key (sk_unprotected);
3962 free_secret_key (sk_protected);
3963 return rc;
3966 /* Get rid of the secret key parameters and store the serial numer. */
3967 sk = sk_unprotected;
3968 n = pubkey_get_nskey (sk->pubkey_algo);
3969 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
3971 gcry_mpi_release (sk->skey[i]);
3972 sk->skey[i] = NULL;
3974 i = pubkey_get_npkey (sk->pubkey_algo);
3975 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
3976 sk->is_protected = 1;
3977 sk->protect.s2k.mode = 1002;
3978 s = get_parameter_value (para, pSERIALNO);
3979 assert (s);
3980 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
3981 sk->protect.ivlen++, s += 2)
3982 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
3984 /* Now write the *protected* secret key to the file. */
3986 char name_buffer[50];
3987 char *fname;
3988 IOBUF fp;
3989 mode_t oldmask;
3991 keyid_from_sk (sk, NULL);
3992 sprintf (name_buffer,"sk_%08lX%08lX.gpg",
3993 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
3995 fname = make_filename (backup_dir, name_buffer, NULL);
3996 oldmask = umask (077);
3997 if (is_secured_filename (fname))
3999 fp = NULL;
4000 errno = EPERM;
4002 else
4003 fp = iobuf_create (fname);
4004 umask (oldmask);
4005 if (!fp)
4007 rc = gpg_error_from_syserror ();
4008 log_error (_("can't create backup file `%s': %s\n"),
4009 fname, strerror(errno) );
4010 xfree (fname);
4011 free_secret_key (sk_unprotected);
4012 free_secret_key (sk_protected);
4013 return rc;
4016 pkt = xcalloc (1, sizeof *pkt);
4017 pkt->pkttype = PKT_SECRET_KEY;
4018 pkt->pkt.secret_key = sk_protected;
4019 sk_protected = NULL;
4021 rc = build_packet (fp, pkt);
4022 if (rc)
4024 log_error("build packet failed: %s\n", g10_errstr(rc) );
4025 iobuf_cancel (fp);
4027 else
4029 unsigned char array[MAX_FINGERPRINT_LEN];
4030 char *fprbuf, *p;
4032 iobuf_close (fp);
4033 iobuf_ioctl (NULL, 2, 0, (char*)fname);
4034 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
4036 fingerprint_from_sk (sk, array, &n);
4037 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4038 for (i=0; i < n ; i++, p += 2)
4039 sprintf (p, "%02X", array[i]);
4040 *p++ = ' ';
4041 *p = 0;
4043 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4044 fprbuf,
4045 fname, strlen (fname),
4047 xfree (fprbuf);
4049 free_packet (pkt);
4050 xfree (pkt);
4051 xfree (fname);
4052 if (rc)
4054 free_secret_key (sk_unprotected);
4055 return rc;
4059 /* Create the public key from the secret key. */
4060 pk = xcalloc (1, sizeof *pk );
4061 pk->timestamp = sk->timestamp;
4062 pk->version = sk->version;
4063 if (expireval)
4064 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4065 pk->pubkey_algo = sk->pubkey_algo;
4066 n = pubkey_get_npkey (sk->pubkey_algo);
4067 for (i=0; i < n; i++)
4068 pk->pkey[i] = mpi_copy (sk->skey[i]);
4070 /* Build packets and add them to the node lists. */
4071 pkt = xcalloc (1,sizeof *pkt);
4072 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4073 pkt->pkt.public_key = pk;
4074 add_kbnode(pub_root, new_kbnode( pkt ));
4076 pkt = xcalloc (1,sizeof *pkt);
4077 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4078 pkt->pkt.secret_key = sk;
4079 add_kbnode(sec_root, new_kbnode( pkt ));
4081 return 0;
4082 #else
4083 return -1;
4084 #endif /*!ENABLE_CARD_SUPPORT*/
4088 #ifdef ENABLE_CARD_SUPPORT
4090 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
4092 int rc;
4093 unsigned char *rsa_n = NULL;
4094 unsigned char *rsa_e = NULL;
4095 unsigned char *rsa_p = NULL;
4096 unsigned char *rsa_q = NULL;
4097 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4098 unsigned char *sexp = NULL;
4099 unsigned char *p;
4100 char numbuf[55], numbuf2[50];
4102 assert (is_RSA (sk->pubkey_algo));
4103 assert (!sk->is_protected);
4105 /* Copy the parameters into straight buffers. */
4106 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4107 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4108 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4109 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4110 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4112 rc = G10ERR_INV_ARG;
4113 goto leave;
4116 /* Put the key into an S-expression. */
4117 sexp = p = xmalloc_secure (30
4118 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4119 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4121 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4122 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4123 p = stpcpy (p, numbuf);
4124 memcpy (p, rsa_n, rsa_n_len);
4125 p += rsa_n_len;
4127 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4128 p = stpcpy (p, numbuf);
4129 memcpy (p, rsa_e, rsa_e_len);
4130 p += rsa_e_len;
4132 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4133 p = stpcpy (p, numbuf);
4134 memcpy (p, rsa_p, rsa_p_len);
4135 p += rsa_p_len;
4137 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4138 p = stpcpy (p, numbuf);
4139 memcpy (p, rsa_q, rsa_q_len);
4140 p += rsa_q_len;
4142 p = stpcpy (p,"))(10:created-at");
4143 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4144 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4145 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4147 /* Fixme: Unfortunately we don't have the serialnumber available -
4148 thus we can't pass it down to the agent. */
4149 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4151 leave:
4152 xfree (sexp);
4153 xfree (rsa_n);
4154 xfree (rsa_e);
4155 xfree (rsa_p);
4156 xfree (rsa_q);
4157 return rc;
4159 #endif /*ENABLE_CARD_SUPPORT*/