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/>.
28 #include <sys/types.h>
43 #include "keyserver-internal.h"
44 #include "call-agent.h"
64 pKEYCREATIONDATE
, /* Same in seconds since epoch. */
66 pKEYEXPIRE
, /* in n seconds */
67 pSUBKEYEXPIRE
, /* in n seconds */
78 struct para_data_s
*next
;
87 struct revocation_key revkey
;
92 struct output_control_s
{
101 armor_filter_context_t
*afx
;
107 armor_filter_context_t
*afx
;
112 struct opaque_data_usage_and_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
,
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
,
138 u32 expireval
, struct para_data_s
*para
,
139 const char *backup_dir
);
143 print_status_key_created (int letter
, PKT_public_key
*pk
, const char *handle
)
145 byte array
[MAX_FINGERPRINT_LEN
], *s
;
152 buf
= xmalloc (MAX_FINGERPRINT_LEN
*2+31 + strlen (handle
) + 1);
159 fingerprint_from_pk (pk
, array
, &n
);
161 for (i
=0; i
< n
; i
++, s
++, p
+= 2)
162 sprintf (p
, "%02X", *s
);
167 for (i
=0; handle
[i
] && i
< 100; i
++)
168 *p
++ = isspace ((unsigned int)handle
[i
])? '_':handle
[i
];
171 write_status_text ((letter
|| pk
)?STATUS_KEY_CREATED
:STATUS_KEY_NOT_CREATED
,
177 print_status_key_not_created (const char *handle
)
179 print_status_key_created (0, NULL
, handle
);
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
) );
199 do_add_key_flags (PKT_signature
*sig
, unsigned int use
)
205 /* The spec says that all primary keys MUST be able to certify. */
206 if(sig
->sig_class
!=0x18)
209 if (use
& PUBKEY_USAGE_SIG
)
211 if (use
& PUBKEY_USAGE_ENC
)
212 buf
[0] |= 0x04 | 0x08;
213 if (use
& PUBKEY_USAGE_AUTH
)
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
;
230 if( pk
->expiredate
) {
231 if(pk
->expiredate
> pk
->timestamp
)
232 u
= pk
->expiredate
- pk
->timestamp
;
236 buf
[0] = (u
>> 24) & 0xff;
237 buf
[1] = (u
>> 16) & 0xff;
238 buf
[2] = (u
>> 8) & 0xff;
240 build_sig_subpkt( sig
, SIGSUBPKT_KEY_EXPIRE
, buf
, 4 );
244 /* Make sure we don't leave a key expiration subpacket lying
246 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_KEY_EXPIRE
);
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
);
262 set_one_pref (int val
, int type
, const char *item
, byte
*buf
, int *nbuf
)
266 for (i
=0; i
< *nbuf
; i
++ )
269 log_info (_("preference `%s' duplicated\n"), item
);
273 if (*nbuf
>= MAX_PREFS
)
276 log_info(_("too many cipher preferences\n"));
278 log_info(_("too many digest preferences\n"));
280 log_info(_("too many compression preferences\n"));
287 buf
[(*nbuf
)++] = val
;
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
;
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
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
329 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256
) )
330 strcat(dummy_string
,"S9 ");
331 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192
) )
332 strcat(dummy_string
,"S8 ");
333 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES
) )
334 strcat(dummy_string
,"S7 ");
335 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5
) )
336 strcat(dummy_string
,"S3 ");
337 strcat(dummy_string
,"S2 "); /* 3DES */
338 /* If we have it, IDEA goes *after* 3DES so it won't be
339 used unless we're encrypting along with a V3 key.
340 Ideally, we would only put the S1 preference in if the
341 key was RSA and <=2048 bits, as that is what won't
342 break PGP2, but that is difficult with the current
343 code, and not really worth checking as a non-RSA <=2048
344 bit key wouldn't be usable by PGP2 anyway. -dms */
345 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA
) )
346 strcat(dummy_string
,"S1 ");
349 strcat(dummy_string
,"H2 ");
351 if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256
))
352 strcat(dummy_string
,"H8 ");
355 strcat(dummy_string
,"H3 ");
358 strcat(dummy_string
,"Z2 ");
360 if(!check_compress_algo(COMPRESS_ALGO_BZIP2
))
361 strcat(dummy_string
,"Z3 ");
364 strcat(dummy_string
,"Z1");
369 else if (!ascii_strcasecmp (string
, "none"))
374 char *tok
,*prefstring
;
376 prefstring
=xstrdup(string
); /* need a writable string! */
378 while((tok
=strsep(&prefstring
," ,")))
380 if((val
=string_to_cipher_algo (tok
)))
382 if(set_one_pref(val
,1,tok
,sym
,&nsym
))
385 else if((val
=string_to_digest_algo (tok
)))
387 if(set_one_pref(val
,2,tok
,hash
,&nhash
))
390 else if((val
=string_to_compress_algo(tok
))>-1)
392 if(set_one_pref(val
,3,tok
,zip
,&nzip
))
395 else if (ascii_strcasecmp(tok
,"mdc")==0)
397 else if (ascii_strcasecmp(tok
,"no-mdc")==0)
399 else if (ascii_strcasecmp(tok
,"ks-modify")==0)
401 else if (ascii_strcasecmp(tok
,"no-ks-modify")==0)
405 log_info (_("invalid item `%s' in preference string\n"),tok
);
407 /* Complain if IDEA is not available. */
408 if(ascii_strcasecmp(tok
,"s1")==0
409 || ascii_strcasecmp(tok
,"idea")==0)
423 if(personal
==PREFTYPE_SYM
)
425 xfree(opt
.personal_cipher_prefs
);
428 opt
.personal_cipher_prefs
=NULL
;
433 opt
.personal_cipher_prefs
=
434 xmalloc(sizeof(prefitem_t
*)*(nsym
+1));
436 for (i
=0; i
<nsym
; i
++)
438 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_SYM
;
439 opt
.personal_cipher_prefs
[i
].value
= sym
[i
];
442 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_NONE
;
443 opt
.personal_cipher_prefs
[i
].value
= 0;
446 else if(personal
==PREFTYPE_HASH
)
448 xfree(opt
.personal_digest_prefs
);
451 opt
.personal_digest_prefs
=NULL
;
456 opt
.personal_digest_prefs
=
457 xmalloc(sizeof(prefitem_t
*)*(nhash
+1));
459 for (i
=0; i
<nhash
; i
++)
461 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_HASH
;
462 opt
.personal_digest_prefs
[i
].value
= hash
[i
];
465 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_NONE
;
466 opt
.personal_digest_prefs
[i
].value
= 0;
469 else if(personal
==PREFTYPE_ZIP
)
471 xfree(opt
.personal_compress_prefs
);
474 opt
.personal_compress_prefs
=NULL
;
479 opt
.personal_compress_prefs
=
480 xmalloc(sizeof(prefitem_t
*)*(nzip
+1));
482 for (i
=0; i
<nzip
; i
++)
484 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_ZIP
;
485 opt
.personal_compress_prefs
[i
].value
= zip
[i
];
488 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_NONE
;
489 opt
.personal_compress_prefs
[i
].value
= 0;
495 memcpy (sym_prefs
, sym
, (nsym_prefs
=nsym
));
496 memcpy (hash_prefs
, hash
, (nhash_prefs
=nhash
));
497 memcpy (zip_prefs
, zip
, (nzip_prefs
=nzip
));
500 prefs_initialized
= 1;
507 /* Return a fake user ID containing the preferences. Caller must
509 PKT_user_id
*keygen_get_std_prefs(void)
512 PKT_user_id
*uid
=xmalloc_clear(sizeof(PKT_user_id
));
514 if(!prefs_initialized
)
515 keygen_set_std_prefs(NULL
,0);
519 uid
->prefs
=xmalloc((sizeof(prefitem_t
*)*
520 (nsym_prefs
+nhash_prefs
+nzip_prefs
+1)));
522 for(i
=0;i
<nsym_prefs
;i
++,j
++)
524 uid
->prefs
[j
].type
=PREFTYPE_SYM
;
525 uid
->prefs
[j
].value
=sym_prefs
[i
];
528 for(i
=0;i
<nhash_prefs
;i
++,j
++)
530 uid
->prefs
[j
].type
=PREFTYPE_HASH
;
531 uid
->prefs
[j
].value
=hash_prefs
[i
];
534 for(i
=0;i
<nzip_prefs
;i
++,j
++)
536 uid
->prefs
[j
].type
=PREFTYPE_ZIP
;
537 uid
->prefs
[j
].value
=zip_prefs
[i
];
540 uid
->prefs
[j
].type
=PREFTYPE_NONE
;
541 uid
->prefs
[j
].value
=0;
543 uid
->flags
.mdc
=mdc_available
;
544 uid
->flags
.ks_modify
=ks_modify
;
550 add_feature_mdc (PKT_signature
*sig
,int enabled
)
557 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
, &n
);
558 /* Already set or cleared */
560 ((enabled
&& (s
[0] & 0x01)) || (!enabled
&& !(s
[0] & 0x01))))
563 if (!s
|| !n
) { /* create a new one */
565 buf
= xmalloc_clear (n
);
573 buf
[0] |= 0x01; /* MDC feature */
577 /* Are there any bits set? */
583 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
);
585 build_sig_subpkt (sig
, SIGSUBPKT_FEATURES
, buf
, n
);
591 add_keyserver_modify (PKT_signature
*sig
,int enabled
)
598 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
601 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
, &n
);
602 /* Already set or cleared */
604 ((enabled
&& (s
[0] & 0x80)) || (!enabled
&& !(s
[0] & 0x80))))
607 if (!s
|| !n
) { /* create a new one */
609 buf
= xmalloc_clear (n
);
617 buf
[0] |= 0x80; /* no-modify flag */
621 /* Are there any bits set? */
627 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
);
629 build_sig_subpkt (sig
, SIGSUBPKT_KS_FLAGS
, buf
, n
);
636 keygen_upd_std_prefs (PKT_signature
*sig
, void *opaque
)
640 if (!prefs_initialized
)
641 keygen_set_std_prefs (NULL
, 0);
644 build_sig_subpkt (sig
, SIGSUBPKT_PREF_SYM
, sym_prefs
, nsym_prefs
);
647 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_SYM
);
648 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_SYM
);
652 build_sig_subpkt (sig
, SIGSUBPKT_PREF_HASH
, hash_prefs
, nhash_prefs
);
655 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_HASH
);
656 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_HASH
);
660 build_sig_subpkt (sig
, SIGSUBPKT_PREF_COMPR
, zip_prefs
, nzip_prefs
);
663 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_COMPR
);
664 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_COMPR
);
667 /* Make sure that the MDC feature flag is set if needed. */
668 add_feature_mdc (sig
,mdc_available
);
669 add_keyserver_modify (sig
,ks_modify
);
670 keygen_add_keyserver_url(sig
,NULL
);
677 * Add preference to the self signature packet.
678 * This is only called for packets with version > 3.
682 keygen_add_std_prefs( PKT_signature
*sig
, void *opaque
)
684 PKT_public_key
*pk
= opaque
;
686 do_add_key_flags (sig
, pk
->pubkey_usage
);
687 keygen_add_key_expire( sig
, opaque
);
688 keygen_upd_std_prefs (sig
, opaque
);
689 keygen_add_keyserver_url(sig
,NULL
);
695 keygen_add_keyserver_url(PKT_signature
*sig
, void *opaque
)
697 const char *url
=opaque
;
700 url
=opt
.def_keyserver_url
;
703 build_sig_subpkt(sig
,SIGSUBPKT_PREF_KS
,url
,strlen(url
));
705 delete_sig_subpkt (sig
->hashed
,SIGSUBPKT_PREF_KS
);
711 keygen_add_notations(PKT_signature
*sig
,void *opaque
)
713 struct notation
*notation
;
715 /* We always start clean */
716 delete_sig_subpkt(sig
->hashed
,SIGSUBPKT_NOTATION
);
717 delete_sig_subpkt(sig
->unhashed
,SIGSUBPKT_NOTATION
);
718 sig
->flags
.notation
=0;
720 for(notation
=opaque
;notation
;notation
=notation
->next
)
721 if(!notation
->flags
.ignore
)
726 n1
=strlen(notation
->name
);
727 if(notation
->altvalue
)
728 n2
=strlen(notation
->altvalue
);
729 else if(notation
->bdat
)
732 n2
=strlen(notation
->value
);
734 buf
= xmalloc( 8 + n1
+ n2
);
736 /* human readable or not */
737 buf
[0] = notation
->bdat
?0:0x80;
738 buf
[1] = buf
[2] = buf
[3] = 0;
743 memcpy(buf
+8, notation
->name
, n1
);
744 if(notation
->altvalue
)
745 memcpy(buf
+8+n1
, notation
->altvalue
, n2
);
746 else if(notation
->bdat
)
747 memcpy(buf
+8+n1
, notation
->bdat
, n2
);
749 memcpy(buf
+8+n1
, notation
->value
, n2
);
750 build_sig_subpkt( sig
, SIGSUBPKT_NOTATION
|
751 (notation
->flags
.critical
?SIGSUBPKT_FLAG_CRITICAL
:0),
760 keygen_add_revkey(PKT_signature
*sig
, void *opaque
)
762 struct revocation_key
*revkey
=opaque
;
763 byte buf
[2+MAX_FINGERPRINT_LEN
];
765 buf
[0]=revkey
->class;
766 buf
[1]=revkey
->algid
;
767 memcpy(&buf
[2],revkey
->fpr
,MAX_FINGERPRINT_LEN
);
769 build_sig_subpkt(sig
,SIGSUBPKT_REV_KEY
,buf
,2+MAX_FINGERPRINT_LEN
);
771 /* All sigs with revocation keys set are nonrevocable */
772 sig
->flags
.revocable
=0;
774 build_sig_subpkt( sig
, SIGSUBPKT_REVOCABLE
, buf
, 1 );
783 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
784 signature creation time. */
786 make_backsig (PKT_signature
*sig
,PKT_public_key
*pk
,
787 PKT_public_key
*sub_pk
,PKT_secret_key
*sub_sk
,
790 PKT_signature
*backsig
;
793 cache_public_key(sub_pk
);
795 rc
= make_keysig_packet (&backsig
, pk
, NULL
, sub_pk
, sub_sk
, 0x19,
796 0, 0, timestamp
, 0, NULL
, NULL
);
798 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc
));
801 /* Get it into a binary packed form. */
802 IOBUF backsig_out
=iobuf_temp();
805 init_packet(&backsig_pkt
);
806 backsig_pkt
.pkttype
=PKT_SIGNATURE
;
807 backsig_pkt
.pkt
.signature
=backsig
;
808 rc
=build_packet(backsig_out
,&backsig_pkt
);
809 free_packet(&backsig_pkt
);
811 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc
));
815 byte
*buf
=iobuf_get_temp_buffer(backsig_out
);
817 /* Remove the packet header */
827 pktlen
=(buf
[1]-192)*256;
833 pktlen
=buf
[2] << 24;
834 pktlen
|=buf
[3] << 16;
853 pktlen
=buf
[mark
++] << 24;
854 pktlen
|=buf
[mark
++] << 16;
857 pktlen
|=buf
[mark
++] << 8;
866 /* Now make the binary blob into a subpacket. */
867 build_sig_subpkt(sig
,SIGSUBPKT_SIGNATURE
,buf
,pktlen
);
869 iobuf_close(backsig_out
);
878 write_direct_sig (KBNODE root
, KBNODE pub_root
, PKT_secret_key
*sk
,
879 struct revocation_key
*revkey
, u32 timestamp
)
888 log_info(_("writing direct signature\n"));
890 /* Get the pk packet from the pub_tree. */
891 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
894 pk
= node
->pkt
->pkt
.public_key
;
896 /* We have to cache the key, so that the verification of the
897 signature creation is able to retrieve the public key. */
898 cache_public_key (pk
);
900 /* Make the signature. */
901 rc
= make_keysig_packet (&sig
,pk
,NULL
,NULL
,sk
,0x1F,
903 keygen_add_revkey
, revkey
);
906 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
910 pkt
= xmalloc_clear( sizeof *pkt
);
911 pkt
->pkttype
= PKT_SIGNATURE
;
912 pkt
->pkt
.signature
= sig
;
913 add_kbnode( root
, new_kbnode( pkt
) );
919 write_selfsigs( KBNODE sec_root
, KBNODE pub_root
, PKT_secret_key
*sk
,
920 unsigned int use
, u32 timestamp
)
930 log_info(_("writing self signature\n"));
932 /* Get the uid packet from the list. */
933 node
= find_kbnode( pub_root
, PKT_USER_ID
);
935 BUG(); /* No user id packet in tree. */
936 uid
= node
->pkt
->pkt
.user_id
;
938 /* Get the pk packet from the pub_tree. */
939 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
942 pk
= node
->pkt
->pkt
.public_key
;
943 pk
->pubkey_usage
= use
;
945 /* We have to cache the key, so that the verification of the
946 signature creation is able to retrieve the public key. */
947 cache_public_key (pk
);
949 /* Make the signature. */
950 rc
= make_keysig_packet (&sig
, pk
, uid
, NULL
, sk
, 0x13,
952 keygen_add_std_prefs
, pk
);
955 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
959 pkt
= xmalloc_clear( sizeof *pkt
);
960 pkt
->pkttype
= PKT_SIGNATURE
;
961 pkt
->pkt
.signature
= sig
;
962 add_kbnode( sec_root
, new_kbnode( pkt
) );
964 pkt
= xmalloc_clear( sizeof *pkt
);
965 pkt
->pkttype
= PKT_SIGNATURE
;
966 pkt
->pkt
.signature
= copy_signature(NULL
,sig
);
967 add_kbnode( pub_root
, new_kbnode( pkt
) );
972 /* Write the key binding signature. If TIMESTAMP is not NULL use the
973 signature creation times. */
975 write_keybinding (KBNODE root
, KBNODE pub_root
,
976 PKT_secret_key
*pri_sk
, PKT_secret_key
*sub_sk
,
977 unsigned int use
, u32 timestamp
)
983 PKT_public_key
*pri_pk
, *sub_pk
;
984 struct opaque_data_usage_and_pk oduap
;
987 log_info(_("writing key binding signature\n"));
989 /* Get the pk packet from the pub_tree. */
990 node
= find_kbnode ( pub_root
, PKT_PUBLIC_KEY
);
993 pri_pk
= node
->pkt
->pkt
.public_key
;
995 /* We have to cache the key, so that the verification of the
996 * signature creation is able to retrieve the public key. */
997 cache_public_key (pri_pk
);
999 /* Find the last subkey. */
1001 for (node
=pub_root
; node
; node
= node
->next
)
1003 if ( node
->pkt
->pkttype
== PKT_PUBLIC_SUBKEY
)
1004 sub_pk
= node
->pkt
->pkt
.public_key
;
1009 /* Make the signature. */
1012 rc
= make_keysig_packet (&sig
, pri_pk
, NULL
, sub_pk
, pri_sk
, 0x18,
1014 keygen_add_key_flags_and_expire
, &oduap
);
1017 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
1021 /* Make a backsig. */
1022 if (use
&PUBKEY_USAGE_SIG
)
1024 rc
= make_backsig (sig
, pri_pk
, sub_pk
, sub_sk
, timestamp
);
1029 pkt
= xmalloc_clear ( sizeof *pkt
);
1030 pkt
->pkttype
= PKT_SIGNATURE
;
1031 pkt
->pkt
.signature
= sig
;
1032 add_kbnode (root
, new_kbnode (pkt
) );
1039 key_from_sexp (gcry_mpi_t
*array
, gcry_sexp_t sexp
,
1040 const char *topname
, const char *elems
)
1042 gcry_sexp_t list
, l2
;
1047 list
= gcry_sexp_find_token (sexp
, topname
, 0);
1049 return gpg_error (GPG_ERR_INV_OBJ
);
1050 l2
= gcry_sexp_cadr (list
);
1051 gcry_sexp_release (list
);
1054 return gpg_error (GPG_ERR_NO_OBJ
);
1056 for (idx
=0,s
=elems
; *s
; s
++, idx
++)
1058 l2
= gcry_sexp_find_token (list
, s
, 1);
1061 rc
= gpg_error (GPG_ERR_NO_OBJ
); /* required parameter not found */
1064 array
[idx
] = gcry_sexp_nth_mpi (l2
, 1, GCRYMPI_FMT_USG
);
1065 gcry_sexp_release (l2
);
1068 rc
= gpg_error (GPG_ERR_INV_OBJ
); /* required parameter invalid */
1072 gcry_sexp_release (list
);
1077 for (i
=0; i
<idx
; i
++)
1082 gcry_sexp_release (list
);
1089 genhelp_protect (DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
*sk
)
1095 sk
->protect
.algo
= dek
->algo
;
1096 sk
->protect
.s2k
= *s2k
;
1097 rc
= protect_secret_key (sk
, dek
);
1099 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc
) );
1106 genhelp_factors (gcry_sexp_t misc_key_info
, KBNODE sec_root
)
1108 (void)misc_key_info
;
1110 #if 0 /* Not used anymore */
1116 /* DSA: don't know whether it makes sense to have the factors, so for now
1117 we store them in the secret keyring (but they are not secret)
1118 p = 2 * q * f1 * f2 * ... * fn
1119 We store only f1 to f_n-1; fn can be calculated because p and q
1121 n
= gcry_sexp_sprint (misc_key_info
, 0, NULL
, 0);
1122 buf
= xmalloc (n
+4);
1123 strcpy (buf
, "#::");
1124 n
= gcry_sexp_sprint (misc_key_info
, 0, buf
+3, n
);
1128 add_kbnode (sec_root
, make_comment_node_from_buffer (buf
, n
));
1131 gcry_sexp_release (misc_key_info
);
1137 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1138 time to be put into the key structure. */
1140 gen_elg (int algo
, unsigned int nbits
,
1141 KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1142 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1143 u32 timestamp
, u32 expireval
, int is_subkey
)
1149 gcry_sexp_t s_parms
, s_key
;
1150 gcry_sexp_t misc_key_info
;
1152 assert( is_ELGAMAL(algo
) );
1157 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1162 nbits
= ((nbits
+ 31) / 32) * 32;
1163 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1167 rc
= gcry_sexp_build ( &s_parms
, NULL
,
1168 "(genkey(%s(nbits %d)))",
1169 algo
== GCRY_PK_ELG_E
? "openpgp-elg" :
1170 algo
== GCRY_PK_ELG
? "elg" : "x-oops" ,
1173 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1175 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1176 gcry_sexp_release (s_parms
);
1179 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1183 sk
= xmalloc_clear( sizeof *sk
);
1184 pk
= xmalloc_clear( sizeof *pk
);
1185 sk
->timestamp
= pk
->timestamp
= timestamp
;
1186 sk
->version
= pk
->version
= 4;
1189 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1191 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1193 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pgy");
1196 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1197 gcry_sexp_release (s_key
);
1198 free_secret_key (sk
);
1199 free_public_key (pk
);
1202 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pgyx");
1205 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1206 gcry_sexp_release (s_key
);
1207 free_secret_key (sk
);
1208 free_public_key (pk
);
1211 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1212 gcry_sexp_release (s_key
);
1214 sk
->is_protected
= 0;
1215 sk
->protect
.algo
= 0;
1217 sk
->csum
= checksum_mpi (sk
->skey
[3]);
1218 if (ret_sk
) /* Return an unprotected version of the sk. */
1219 *ret_sk
= copy_secret_key ( NULL
, sk
);
1221 rc
= genhelp_protect (dek
, s2k
, sk
);
1224 free_public_key (pk
);
1225 free_secret_key (sk
);
1226 gcry_sexp_release (misc_key_info
);
1230 pkt
= xmalloc_clear (sizeof *pkt
);
1231 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1232 pkt
->pkt
.public_key
= pk
;
1233 add_kbnode (pub_root
, new_kbnode( pkt
));
1235 /* Don't know whether it makes sense to have access to the factors,
1236 so for now we store them in the secret keyring (but they are not
1238 pkt
= xmalloc_clear (sizeof *pkt
);
1239 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1240 pkt
->pkt
.secret_key
= sk
;
1241 add_kbnode (sec_root
, new_kbnode( pkt
));
1243 genhelp_factors (misc_key_info
, sec_root
);
1250 * Generate a DSA key
1253 gen_dsa (unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1254 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1255 u32 timestamp
, u32 expireval
, int is_subkey
)
1261 gcry_sexp_t s_parms
, s_key
;
1262 gcry_sexp_t misc_key_info
;
1265 if ( nbits
< 512 || (!opt
.flags
.dsa2
&& nbits
> 1024))
1268 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1270 else if ( nbits
> 3072 )
1273 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1278 nbits
= ((nbits
+ 63) / 64) * 64;
1279 log_info(_("keysize rounded up to %u bits\n"), nbits
);
1283 Figure out a q size based on the key size. FIPS 180-3 says:
1290 2048/256 is an odd pair since there is also a 2048/224 and
1291 3072/256. Matching sizes is not a very exact science.
1293 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1294 but less than 2048, and 160 for 1024 (DSA1).
1299 else if ( nbits
> 1024)
1305 log_info (_("WARNING: some OpenPGP programs can't"
1306 " handle a DSA key with this digest size\n"));
1308 rc
= gcry_sexp_build (&s_parms
, NULL
,
1309 "(genkey(dsa(nbits %d)(qbits %d)))",
1310 (int)nbits
, (int)qbits
);
1312 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1314 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1315 gcry_sexp_release (s_parms
);
1318 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1322 sk
= xmalloc_clear( sizeof *sk
);
1323 pk
= xmalloc_clear( sizeof *pk
);
1324 sk
->timestamp
= pk
->timestamp
= timestamp
;
1325 sk
->version
= pk
->version
= 4;
1327 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1328 sk
->pubkey_algo
= pk
->pubkey_algo
= PUBKEY_ALGO_DSA
;
1330 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pqgy");
1333 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1334 gcry_sexp_release (s_key
);
1335 free_public_key(pk
);
1336 free_secret_key(sk
);
1339 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pqgyx");
1342 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1343 gcry_sexp_release (s_key
);
1344 free_public_key(pk
);
1345 free_secret_key(sk
);
1348 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1349 gcry_sexp_release (s_key
);
1351 sk
->is_protected
= 0;
1352 sk
->protect
.algo
= 0;
1354 sk
->csum
= checksum_mpi ( sk
->skey
[4] );
1355 if( ret_sk
) /* return an unprotected version of the sk */
1356 *ret_sk
= copy_secret_key( NULL
, sk
);
1358 rc
= genhelp_protect (dek
, s2k
, sk
);
1361 free_public_key (pk
);
1362 free_secret_key (sk
);
1363 gcry_sexp_release (misc_key_info
);
1367 pkt
= xmalloc_clear(sizeof *pkt
);
1368 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1369 pkt
->pkt
.public_key
= pk
;
1370 add_kbnode(pub_root
, new_kbnode( pkt
));
1372 /* Don't know whether it makes sense to have the factors, so for now
1373 * we store them in the secret keyring (but they are not secret)
1374 * p = 2 * q * f1 * f2 * ... * fn
1375 * We store only f1 to f_n-1; fn can be calculated because p and q
1378 pkt
= xmalloc_clear(sizeof *pkt
);
1379 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1380 pkt
->pkt
.secret_key
= sk
;
1381 add_kbnode(sec_root
, new_kbnode( pkt
));
1383 genhelp_factors (misc_key_info
, sec_root
);
1390 * Generate an RSA key.
1393 gen_rsa (int algo
, unsigned nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1394 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1395 u32 timestamp
, u32 expireval
, int is_subkey
)
1401 gcry_sexp_t s_parms
, s_key
;
1403 assert (is_RSA(algo
));
1408 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1413 nbits
= ((nbits
+ 31) / 32) * 32;
1414 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1417 rc
= gcry_sexp_build (&s_parms
, NULL
,
1418 "(genkey(rsa(nbits %d)))",
1421 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1423 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1424 gcry_sexp_release (s_parms
);
1427 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1431 sk
= xmalloc_clear( sizeof *sk
);
1432 pk
= xmalloc_clear( sizeof *pk
);
1433 sk
->timestamp
= pk
->timestamp
= timestamp
;
1434 sk
->version
= pk
->version
= 4;
1437 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1439 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1441 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "ne");
1444 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1445 gcry_sexp_release (s_key
);
1446 free_public_key(pk
);
1447 free_secret_key(sk
);
1450 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
1453 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1454 gcry_sexp_release (s_key
);
1455 free_public_key(pk
);
1456 free_secret_key(sk
);
1459 gcry_sexp_release (s_key
);
1461 sk
->is_protected
= 0;
1462 sk
->protect
.algo
= 0;
1464 sk
->csum
= checksum_mpi (sk
->skey
[2] );
1465 sk
->csum
+= checksum_mpi (sk
->skey
[3] );
1466 sk
->csum
+= checksum_mpi (sk
->skey
[4] );
1467 sk
->csum
+= checksum_mpi (sk
->skey
[5] );
1468 if( ret_sk
) /* return an unprotected version of the sk */
1469 *ret_sk
= copy_secret_key( NULL
, sk
);
1471 rc
= genhelp_protect (dek
, s2k
, sk
);
1474 free_public_key (pk
);
1475 free_secret_key (sk
);
1479 pkt
= xmalloc_clear(sizeof *pkt
);
1480 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1481 pkt
->pkt
.public_key
= pk
;
1482 add_kbnode(pub_root
, new_kbnode( pkt
));
1484 pkt
= xmalloc_clear(sizeof *pkt
);
1485 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1486 pkt
->pkt
.secret_key
= sk
;
1487 add_kbnode(sec_root
, new_kbnode( pkt
));
1495 * return 0 on error or the multiplier
1498 check_valid_days( const char *s
)
1508 return 0; /* e.g. "2323wc" */
1509 if( *s
== 'd' || *s
== 'D' )
1511 if( *s
== 'w' || *s
== 'W' )
1513 if( *s
== 'm' || *s
== 'M' )
1515 if( *s
== 'y' || *s
== 'Y' )
1522 print_key_flags(int flags
)
1524 if(flags
&PUBKEY_USAGE_SIG
)
1525 tty_printf("%s ",_("Sign"));
1527 if(flags
&PUBKEY_USAGE_CERT
)
1528 tty_printf("%s ",_("Certify"));
1530 if(flags
&PUBKEY_USAGE_ENC
)
1531 tty_printf("%s ",_("Encrypt"));
1533 if(flags
&PUBKEY_USAGE_AUTH
)
1534 tty_printf("%s ",_("Authenticate"));
1538 /* Returns the key flags */
1540 ask_key_flags(int algo
,int subkey
)
1542 /* TRANSLATORS: Please use only plain ASCII characters for the
1543 translation. If this is not possible use single digits. The
1544 string needs to 8 bytes long. Here is a description of the
1547 s = Toggle signing capability
1548 e = Toggle encryption capability
1549 a = Toggle authentication capability
1552 const char *togglers
=_("SsEeAaQq");
1554 unsigned int current
=0;
1555 unsigned int possible
=openpgp_pk_algo_usage(algo
);
1557 if ( strlen(togglers
) != 7 )
1559 tty_printf ("NOTE: Bad translation at %s:%d. "
1560 "Please report.\n", __FILE__
, __LINE__
);
1561 togglers
= "11223300";
1564 /* Only primary keys may certify. */
1566 possible
&=~PUBKEY_USAGE_CERT
;
1568 /* Preload the current set with the possible set, minus
1569 authentication, since nobody really uses auth yet. */
1570 current
=possible
&~PUBKEY_USAGE_AUTH
;
1575 tty_printf(_("Possible actions for a %s key: "),
1576 gcry_pk_algo_name (algo
));
1577 print_key_flags(possible
);
1579 tty_printf(_("Current allowed actions: "));
1580 print_key_flags(current
);
1583 if(possible
&PUBKEY_USAGE_SIG
)
1584 tty_printf(_(" (%c) Toggle the sign capability\n"),
1586 if(possible
&PUBKEY_USAGE_ENC
)
1587 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1589 if(possible
&PUBKEY_USAGE_AUTH
)
1590 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1593 tty_printf(_(" (%c) Finished\n"),togglers
[6]);
1597 answer
= cpr_get("keygen.flags",_("Your selection? "));
1600 if(strlen(answer
)>1)
1601 tty_printf(_("Invalid selection.\n"));
1602 else if(*answer
=='\0' || *answer
==togglers
[6] || *answer
==togglers
[7])
1604 else if((*answer
==togglers
[0] || *answer
==togglers
[1])
1605 && possible
&PUBKEY_USAGE_SIG
)
1607 if(current
&PUBKEY_USAGE_SIG
)
1608 current
&=~PUBKEY_USAGE_SIG
;
1610 current
|=PUBKEY_USAGE_SIG
;
1612 else if((*answer
==togglers
[2] || *answer
==togglers
[3])
1613 && possible
&PUBKEY_USAGE_ENC
)
1615 if(current
&PUBKEY_USAGE_ENC
)
1616 current
&=~PUBKEY_USAGE_ENC
;
1618 current
|=PUBKEY_USAGE_ENC
;
1620 else if((*answer
==togglers
[4] || *answer
==togglers
[5])
1621 && possible
&PUBKEY_USAGE_AUTH
)
1623 if(current
&PUBKEY_USAGE_AUTH
)
1624 current
&=~PUBKEY_USAGE_AUTH
;
1626 current
|=PUBKEY_USAGE_AUTH
;
1629 tty_printf(_("Invalid selection.\n"));
1639 * Returns: 0 to create both a DSA and a Elgamal key.
1640 * and only if key flags are to be written the desired usage.
1643 ask_algo (int addmode
, unsigned int *r_usage
)
1649 tty_printf(_("Please select what kind of key you want:\n"));
1651 tty_printf(_(" (%d) DSA and Elgamal (default)\n"), 1 );
1652 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
1654 tty_printf( _(" (%d) DSA (set your own capabilities)\n"), 3 );
1656 tty_printf(_(" (%d) Elgamal (encrypt only)\n"), 4 );
1657 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
1659 tty_printf(_(" (%d) RSA (encrypt only)\n"), 6 );
1661 tty_printf( _(" (%d) RSA (set your own capabilities)\n"), 7 );
1664 answer
= cpr_get("keygen.algo",_("Your selection? "));
1666 algo
= *answer
? atoi(answer
): 1;
1668 if( algo
== 1 && !addmode
) {
1669 algo
= 0; /* create both keys */
1672 else if( algo
== 7 && opt
.expert
) {
1673 algo
= PUBKEY_ALGO_RSA
;
1674 *r_usage
=ask_key_flags(algo
,addmode
);
1677 else if( algo
== 6 && addmode
) {
1678 algo
= PUBKEY_ALGO_RSA
;
1679 *r_usage
= PUBKEY_USAGE_ENC
;
1682 else if( algo
== 5 ) {
1683 algo
= PUBKEY_ALGO_RSA
;
1684 *r_usage
= PUBKEY_USAGE_SIG
;
1687 else if( algo
== 4 && addmode
) {
1688 algo
= PUBKEY_ALGO_ELGAMAL_E
;
1689 *r_usage
= PUBKEY_USAGE_ENC
;
1692 else if( algo
== 3 && opt
.expert
) {
1693 algo
= PUBKEY_ALGO_DSA
;
1694 *r_usage
=ask_key_flags(algo
,addmode
);
1697 else if( algo
== 2 ) {
1698 algo
= PUBKEY_ALGO_DSA
;
1699 *r_usage
= PUBKEY_USAGE_SIG
;
1703 tty_printf(_("Invalid selection.\n"));
1711 ask_keysize( int algo
)
1713 unsigned int nbits
, min
, def
=2048, max
=4096;
1722 case PUBKEY_ALGO_DSA
:
1730 tty_printf(_("DSA keypair will have %u bits.\n"),1024);
1735 case PUBKEY_ALGO_RSA
:
1740 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1741 gcry_pk_algo_name (algo
), min
, max
);
1745 char *prompt
,*answer
;
1747 #define PROMPTSTRING _("What keysize do you want? (%u) ")
1749 prompt
=xmalloc(strlen(PROMPTSTRING
)+20);
1750 sprintf(prompt
,PROMPTSTRING
,def
);
1754 answer
= cpr_get("keygen.size",prompt
);
1756 nbits
= *answer
? atoi(answer
): def
;
1760 if(nbits
<min
|| nbits
>max
)
1761 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1762 gcry_pk_algo_name (algo
), min
, max
);
1767 tty_printf(_("Requested keysize is %u bits\n"), nbits
);
1769 if( algo
== PUBKEY_ALGO_DSA
&& (nbits
% 64) )
1771 nbits
= ((nbits
+ 63) / 64) * 64;
1772 tty_printf(_("rounded up to %u bits\n"), nbits
);
1774 else if( (nbits
% 32) )
1776 nbits
= ((nbits
+ 31) / 32) * 32;
1777 tty_printf(_("rounded up to %u bits\n"), nbits
);
1785 * Parse an expire string and return its value in seconds.
1786 * Returns (u32)-1 on error.
1787 * This isn't perfect since scan_isodatestr returns unix time, and
1788 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1789 * Because of this, we only permit setting expirations up to 2106, but
1790 * OpenPGP could theoretically allow up to 2242. I think we'll all
1791 * just cope for the next few years until we get a 64-bit time_t or
1795 parse_expire_string( const char *string
)
1800 u32 curtime
= make_timestamp ();
1804 else if (!strncmp (string
, "seconds=", 8))
1805 seconds
= atoi (string
+8);
1806 else if ((abs_date
= scan_isodatestr(string
)) && abs_date
> curtime
)
1807 seconds
= abs_date
- curtime
;
1808 else if ((mult
= check_valid_days (string
)))
1809 seconds
= atoi (string
) * 86400L * mult
;
1811 seconds
= (u32
)(-1);
1816 /* Parsean Creation-Date string which is either "1986-04-26" or
1817 "19860426T042640". Returns 0 on error. */
1819 parse_creation_string (const char *string
)
1825 else if ( !strncmp (string
, "seconds=", 8) )
1826 seconds
= atoi (string
+8);
1827 else if ( !(seconds
= scan_isodatestr (string
)))
1829 time_t tmp
= isotime2epoch (string
);
1830 seconds
= (tmp
== (time_t)(-1))? 0 : tmp
;
1836 /* object == 0 for a key, and 1 for a sig */
1838 ask_expire_interval(int object
,const char *def_expire
)
1848 tty_printf(_("Please specify how long the key should be valid.\n"
1849 " 0 = key does not expire\n"
1850 " <n> = key expires in n days\n"
1851 " <n>w = key expires in n weeks\n"
1852 " <n>m = key expires in n months\n"
1853 " <n>y = key expires in n years\n"));
1859 tty_printf(_("Please specify how long the signature should be valid.\n"
1860 " 0 = signature does not expire\n"
1861 " <n> = signature expires in n days\n"
1862 " <n>w = signature expires in n weeks\n"
1863 " <n>m = signature expires in n months\n"
1864 " <n>y = signature expires in n years\n"));
1871 /* Note: The elgamal subkey for DSA has no expiration date because
1872 * it must be signed with the DSA key and this one has the expiration
1878 u32 curtime
=make_timestamp();
1882 answer
= cpr_get("keygen.valid",_("Key is valid for? (0) "));
1887 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1888 /* This will actually end up larger than necessary because
1889 of the 2 bytes for '%s' */
1890 prompt
=xmalloc(strlen(PROMPTSTRING
)+strlen(def_expire
)+1);
1891 sprintf(prompt
,PROMPTSTRING
,def_expire
);
1894 answer
= cpr_get("siggen.valid",prompt
);
1898 answer
=xstrdup(def_expire
);
1901 trim_spaces(answer
);
1902 interval
= parse_expire_string( answer
);
1903 if( interval
== (u32
)-1 )
1905 tty_printf(_("invalid value\n"));
1911 tty_printf((object
==0)
1912 ? _("Key does not expire at all\n")
1913 : _("Signature does not expire at all\n"));
1917 tty_printf(object
==0
1918 ? _("Key expires at %s\n")
1919 : _("Signature expires at %s\n"),
1920 asctimestamp((ulong
)(curtime
+ interval
) ) );
1921 #if SIZEOF_TIME_T <= 4
1922 if ( (time_t)((ulong
)(curtime
+interval
)) < 0 )
1923 tty_printf (_("Your system can't display dates beyond 2038.\n"
1924 "However, it will be correctly handled up to"
1927 #endif /*SIZEOF_TIME_T*/
1928 if ( (time_t)((unsigned long)(curtime
+interval
)) < curtime
)
1930 tty_printf (_("invalid value\n"));
1935 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1936 _("Is this correct? (y/N) ")) )
1947 u32 x
= ask_expire_interval(0,NULL
);
1948 return x
? make_timestamp() + x
: 0;
1953 ask_user_id( int mode
)
1956 char *aname
, *acomment
, *amail
, *uid
;
1962 "GnuPG needs to construct a user ID to identify your key.\n"
1964 const char *s2
= _(s1
);
1966 if (!strcmp (s1
, s2
))
1968 /* There is no translation for the string thus we to use
1969 the old info text. gettext has no way to tell whether
1970 a translation is actually available, thus we need to
1971 to compare again. */
1972 const char *s3
= N_("\n"
1973 "You need a user ID to identify your key; "
1974 "the software constructs the user ID\n"
1975 "from the Real Name, Comment and Email Address in this form:\n"
1976 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
1977 const char *s4
= _(s3
);
1978 if (strcmp (s3
, s4
))
1979 s2
= s3
; /* A translation exists - use it. */
1981 tty_printf ("%s", s2
) ;
1983 uid
= aname
= acomment
= amail
= NULL
;
1991 aname
= cpr_get("keygen.name",_("Real name: "));
1995 if( opt
.allow_freeform_uid
)
1998 if( strpbrk( aname
, "<>" ) )
1999 tty_printf(_("Invalid character in name\n"));
2000 else if( digitp(aname
) )
2001 tty_printf(_("Name may not start with a digit\n"));
2002 else if( strlen(aname
) < 5 )
2003 tty_printf(_("Name must be at least 5 characters long\n"));
2011 amail
= cpr_get("keygen.email",_("Email address: "));
2014 if( !*amail
|| opt
.allow_freeform_uid
)
2015 break; /* no email address is okay */
2016 else if ( !is_valid_mailbox (amail
) )
2017 tty_printf(_("Not a valid email address\n"));
2025 acomment
= cpr_get("keygen.comment",_("Comment: "));
2026 trim_spaces(acomment
);
2029 break; /* no comment is okay */
2030 else if( strpbrk( acomment
, "()" ) )
2031 tty_printf(_("Invalid character in comment\n"));
2039 uid
= p
= xmalloc(strlen(aname
)+strlen(amail
)+strlen(acomment
)+12+10);
2040 p
= stpcpy(p
, aname
);
2042 p
= stpcpy(stpcpy(stpcpy(p
," ("), acomment
),")");
2044 p
= stpcpy(stpcpy(stpcpy(p
," <"), amail
),">");
2046 /* Append a warning if the RNG is switched into fake mode. */
2047 if ( random_is_faked () )
2048 strcpy(p
, " (insecure!)" );
2050 /* print a note in case that UTF8 mapping has to be done */
2051 for(p
=uid
; *p
; p
++ ) {
2053 tty_printf(_("You are using the `%s' character set.\n"),
2054 get_native_charset() );
2059 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid
);
2060 /* fixme: add a warning if this user-id already exists */
2061 if( !*amail
&& !opt
.allow_freeform_uid
2062 && (strchr( aname
, '@' ) || strchr( acomment
, '@'))) {
2064 tty_printf(_("Please don't put the email address "
2065 "into the real name or the comment\n") );
2069 /* TRANSLATORS: These are the allowed answers in
2070 lower and uppercase. Below you will find the matching
2071 string which should be translated accordingly and the
2072 letter changed to match the one in the answer string.
2077 o = Okay (ready, continue)
2080 const char *ansstr
= _("NnCcEeOoQq");
2082 if( strlen(ansstr
) != 10 )
2084 if( cpr_enabled() ) {
2085 answer
= xstrdup(ansstr
+6);
2089 answer
= cpr_get("keygen.userid.cmd", fail
?
2090 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2091 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2094 if( strlen(answer
) > 1 )
2096 else if( *answer
== ansstr
[0] || *answer
== ansstr
[1] ) {
2097 xfree(aname
); aname
= NULL
;
2100 else if( *answer
== ansstr
[2] || *answer
== ansstr
[3] ) {
2101 xfree(acomment
); acomment
= NULL
;
2104 else if( *answer
== ansstr
[4] || *answer
== ansstr
[5] ) {
2105 xfree(amail
); amail
= NULL
;
2108 else if( *answer
== ansstr
[6] || *answer
== ansstr
[7] ) {
2110 tty_printf(_("Please correct the error first\n"));
2113 xfree(aname
); aname
= NULL
;
2114 xfree(acomment
); acomment
= NULL
;
2115 xfree(amail
); amail
= NULL
;
2119 else if( *answer
== ansstr
[8] || *answer
== ansstr
[9] ) {
2120 xfree(aname
); aname
= NULL
;
2121 xfree(acomment
); acomment
= NULL
;
2122 xfree(amail
); amail
= NULL
;
2123 xfree(uid
); uid
= NULL
;
2129 if( !amail
&& !acomment
&& !amail
)
2131 xfree(uid
); uid
= NULL
;
2134 char *p
= native_to_utf8( uid
);
2143 do_ask_passphrase ( STRING2KEY
**ret_s2k
, int *r_canceled
)
2147 const char *errtext
= NULL
;
2149 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2151 s2k
= xmalloc_secure( sizeof *s2k
);
2153 s2k
->mode
= opt
.s2k_mode
;
2154 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2155 dek
= passphrase_to_dek( NULL
, 0, opt
.s2k_cipher_algo
, s2k
,2,
2156 errtext
, r_canceled
);
2157 if (!dek
&& *r_canceled
) {
2158 xfree(dek
); dek
= NULL
;
2159 xfree(s2k
); s2k
= NULL
;
2163 errtext
= N_("passphrase not correctly repeated; try again");
2164 tty_printf(_("%s.\n"), _(errtext
));
2166 else if( !dek
->keylen
) {
2167 xfree(dek
); dek
= NULL
;
2168 xfree(s2k
); s2k
= NULL
;
2170 "You don't want a passphrase - this is probably a *bad* idea!\n"
2171 "I will do it anyway. You can change your passphrase at any time,\n"
2172 "using this program with the option \"--edit-key\".\n\n"));
2183 /* Basic key generation. Here we divert to the actual generation
2184 routines based on the requested algorithm. */
2186 do_create (int algo
, unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
,
2187 DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
**sk
,
2188 u32 timestamp
, u32 expiredate
, int is_subkey
)
2194 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2195 "some other action (type on the keyboard, move the mouse, utilize the\n"
2196 "disks) during the prime generation; this gives the random number\n"
2197 "generator a better chance to gain enough entropy.\n") );
2199 if( algo
== PUBKEY_ALGO_ELGAMAL_E
)
2200 rc
= gen_elg(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2201 timestamp
, expiredate
, is_subkey
);
2202 else if( algo
== PUBKEY_ALGO_DSA
)
2203 rc
= gen_dsa(nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2204 timestamp
, expiredate
, is_subkey
);
2205 else if( algo
== PUBKEY_ALGO_RSA
)
2206 rc
= gen_rsa(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2207 timestamp
, expiredate
, is_subkey
);
2216 * Generate a new user id packet, or return NULL if canceled
2225 p
= ask_user_id( 1 );
2229 uid
= xmalloc_clear( sizeof *uid
+ n
);
2231 strcpy(uid
->name
, p
);
2238 release_parameter_list( struct para_data_s
*r
)
2240 struct para_data_s
*r2
;
2242 for( ; r
; r
= r2
) {
2244 if( r
->key
== pPASSPHRASE_DEK
)
2246 else if( r
->key
== pPASSPHRASE_S2K
)
2253 static struct para_data_s
*
2254 get_parameter( struct para_data_s
*para
, enum para_name key
)
2256 struct para_data_s
*r
;
2258 for( r
= para
; r
&& r
->key
!= key
; r
= r
->next
)
2264 get_parameter_value( struct para_data_s
*para
, enum para_name key
)
2266 struct para_data_s
*r
= get_parameter( para
, key
);
2267 return (r
&& *r
->u
.value
)? r
->u
.value
: NULL
;
2271 get_parameter_algo( struct para_data_s
*para
, enum para_name key
)
2274 struct para_data_s
*r
= get_parameter( para
, key
);
2277 if( digitp( r
->u
.value
) )
2278 i
= atoi( r
->u
.value
);
2279 else if ( !strcmp ( r
->u
.value
, "ELG-E")
2280 || !strcmp ( r
->u
.value
, "ELG") )
2283 i
= gcry_pk_map_name (r
->u
.value
);
2284 if (i
== PUBKEY_ALGO_RSA_E
|| i
== PUBKEY_ALGO_RSA_S
)
2285 i
= 0; /* we don't want to allow generation of these algorithms */
2290 * parse the usage parameter and set the keyflags. Return true on error.
2293 parse_parameter_usage (const char *fname
,
2294 struct para_data_s
*para
, enum para_name key
)
2296 struct para_data_s
*r
= get_parameter( para
, key
);
2301 return 0; /* none (this is an optional parameter)*/
2305 while ( (p
= strsep (&pn
, " \t,")) ) {
2308 else if ( !ascii_strcasecmp (p
, "sign") )
2309 use
|= PUBKEY_USAGE_SIG
;
2310 else if ( !ascii_strcasecmp (p
, "encrypt") )
2311 use
|= PUBKEY_USAGE_ENC
;
2312 else if ( !ascii_strcasecmp (p
, "auth") )
2313 use
|= PUBKEY_USAGE_AUTH
;
2315 log_error("%s:%d: invalid usage list\n", fname
, r
->lnr
);
2316 return -1; /* error */
2324 parse_revocation_key (const char *fname
,
2325 struct para_data_s
*para
, enum para_name key
)
2327 struct para_data_s
*r
= get_parameter( para
, key
);
2328 struct revocation_key revkey
;
2333 return 0; /* none (this is an optional parameter) */
2338 revkey
.algid
=atoi(pn
);
2342 /* Skip to the fpr */
2343 while(*pn
&& *pn
!=':')
2351 for(i
=0;i
<MAX_FINGERPRINT_LEN
&& *pn
;i
++,pn
+=2)
2353 int c
=hextobyte(pn
);
2360 /* skip to the tag */
2361 while(*pn
&& *pn
!='s' && *pn
!='S')
2364 if(ascii_strcasecmp(pn
,"sensitive")==0)
2367 memcpy(&r
->u
.revkey
,&revkey
,sizeof(struct revocation_key
));
2372 log_error("%s:%d: invalid revocation key\n", fname
, r
->lnr
);
2373 return -1; /* error */
2378 get_parameter_u32( struct para_data_s
*para
, enum para_name key
)
2380 struct para_data_s
*r
= get_parameter( para
, key
);
2384 if( r
->key
== pKEYCREATIONDATE
)
2385 return r
->u
.creation
;
2386 if( r
->key
== pKEYEXPIRE
|| r
->key
== pSUBKEYEXPIRE
)
2388 if( r
->key
== pKEYUSAGE
|| r
->key
== pSUBKEYUSAGE
)
2391 return (unsigned int)strtoul( r
->u
.value
, NULL
, 10 );
2395 get_parameter_uint( struct para_data_s
*para
, enum para_name key
)
2397 return get_parameter_u32( para
, key
);
2401 get_parameter_dek( struct para_data_s
*para
, enum para_name key
)
2403 struct para_data_s
*r
= get_parameter( para
, key
);
2404 return r
? r
->u
.dek
: NULL
;
2408 get_parameter_s2k( struct para_data_s
*para
, enum para_name key
)
2410 struct para_data_s
*r
= get_parameter( para
, key
);
2411 return r
? r
->u
.s2k
: NULL
;
2414 static struct revocation_key
*
2415 get_parameter_revkey( struct para_data_s
*para
, enum para_name key
)
2417 struct para_data_s
*r
= get_parameter( para
, key
);
2418 return r
? &r
->u
.revkey
: NULL
;
2422 proc_parameter_file( struct para_data_s
*para
, const char *fname
,
2423 struct output_control_s
*outctrl
, int card
)
2425 struct para_data_s
*r
;
2426 const char *s1
, *s2
, *s3
;
2429 int have_user_id
=0,err
,algo
;
2431 /* Check that we have all required parameters. */
2432 r
= get_parameter( para
, pKEYTYPE
);
2435 algo
=get_parameter_algo(para
,pKEYTYPE
);
2436 if (openpgp_pk_test_algo2 (algo
, PUBKEY_USAGE_SIG
))
2438 log_error("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2444 log_error("%s: no Key-Type specified\n",fname
);
2448 err
=parse_parameter_usage (fname
, para
, pKEYUSAGE
);
2451 /* Default to algo capabilities if key-usage is not provided */
2452 r
=xmalloc_clear(sizeof(*r
));
2454 r
->u
.usage
=openpgp_pk_algo_usage(algo
);
2461 r
= get_parameter( para
, pSUBKEYTYPE
);
2464 algo
=get_parameter_algo( para
, pSUBKEYTYPE
);
2465 if (openpgp_pk_test_algo (algo
))
2467 log_error("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2471 err
=parse_parameter_usage (fname
, para
, pSUBKEYUSAGE
);
2474 /* Default to algo capabilities if subkey-usage is not
2476 r
=xmalloc_clear(sizeof(*r
));
2477 r
->key
=pSUBKEYUSAGE
;
2478 r
->u
.usage
=openpgp_pk_algo_usage(algo
);
2486 if( get_parameter_value( para
, pUSERID
) )
2490 /* create the formatted user ID */
2491 s1
= get_parameter_value( para
, pNAMEREAL
);
2492 s2
= get_parameter_value( para
, pNAMECOMMENT
);
2493 s3
= get_parameter_value( para
, pNAMEEMAIL
);
2494 if( s1
|| s2
|| s3
)
2496 n
= (s1
?strlen(s1
):0) + (s2
?strlen(s2
):0) + (s3
?strlen(s3
):0);
2497 r
= xmalloc_clear( sizeof *r
+ n
+ 20 );
2503 p
= stpcpy(stpcpy(stpcpy(p
," ("), s2
),")");
2505 p
= stpcpy(stpcpy(stpcpy(p
," <"), s3
),">");
2514 log_error("%s: no User-ID specified\n",fname
);
2518 /* Set preferences, if any. */
2519 keygen_set_std_prefs(get_parameter_value( para
, pPREFERENCES
), 0);
2521 /* Set keyserver, if any. */
2522 s1
=get_parameter_value( para
, pKEYSERVER
);
2525 struct keyserver_spec
*spec
;
2527 spec
=parse_keyserver_uri(s1
,1,NULL
,0);
2530 free_keyserver_spec(spec
);
2531 opt
.def_keyserver_url
=s1
;
2535 log_error("%s:%d: invalid keyserver url\n", fname
, r
->lnr
);
2540 /* Set revoker, if any. */
2541 if (parse_revocation_key (fname
, para
, pREVOKER
))
2544 /* Make DEK and S2K from the Passphrase. */
2545 if (outctrl
->ask_passphrase
)
2547 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2548 feature is required so that GUIs are able to do a key
2549 creation but have gpg-agent ask for the passphrase. */
2554 dek
= do_ask_passphrase ( &s2k
, &canceled
);
2557 r
= xmalloc_clear( sizeof *r
);
2558 r
->key
= pPASSPHRASE_DEK
;
2562 r
= xmalloc_clear( sizeof *r
);
2563 r
->key
= pPASSPHRASE_S2K
;
2571 log_error ("%s:%d: key generation canceled\n", fname
, r
->lnr
);
2577 r
= get_parameter( para
, pPASSPHRASE
);
2578 if ( r
&& *r
->u
.value
)
2580 /* We have a plain text passphrase - create a DEK from it.
2581 * It is a little bit ridiculous to keep it in secure memory
2582 * but because we do this always, why not here. */
2586 s2k
= xmalloc_secure ( sizeof *s2k
);
2587 s2k
->mode
= opt
.s2k_mode
;
2588 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2589 set_next_passphrase ( r
->u
.value
);
2590 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2592 set_next_passphrase (NULL
);
2594 memset (r
->u
.value
, 0, strlen(r
->u
.value
));
2596 r
= xmalloc_clear (sizeof *r
);
2597 r
->key
= pPASSPHRASE_S2K
;
2601 r
= xmalloc_clear (sizeof *r
);
2602 r
->key
= pPASSPHRASE_DEK
;
2609 /* Make KEYCREATIONDATE from Creation-Date. */
2610 r
= get_parameter (para
, pCREATIONDATE
);
2611 if (r
&& *r
->u
.value
)
2615 seconds
= parse_creation_string (r
->u
.value
);
2618 log_error ("%s:%d: invalid creation date\n", fname
, r
->lnr
);
2621 r
->u
.creation
= seconds
;
2622 r
->key
= pKEYCREATIONDATE
; /* Change that entry. */
2625 /* Make KEYEXPIRE from Expire-Date. */
2626 r
= get_parameter( para
, pEXPIREDATE
);
2627 if( r
&& *r
->u
.value
)
2631 seconds
= parse_expire_string( r
->u
.value
);
2632 if( seconds
== (u32
)-1 )
2634 log_error("%s:%d: invalid expire date\n", fname
, r
->lnr
);
2637 r
->u
.expire
= seconds
;
2638 r
->key
= pKEYEXPIRE
; /* change hat entry */
2639 /* also set it for the subkey */
2640 r
= xmalloc_clear( sizeof *r
+ 20 );
2641 r
->key
= pSUBKEYEXPIRE
;
2642 r
->u
.expire
= seconds
;
2647 if( !!outctrl
->pub
.newfname
^ !!outctrl
->sec
.newfname
) {
2648 log_error("%s:%d: only one ring name is set\n", fname
, outctrl
->lnr
);
2652 do_generate_keypair( para
, outctrl
, card
);
2658 * Kludge to allow non interactive key generation controlled
2659 * by a parameter file.
2660 * Note, that string parameters are expected to be in UTF-8
2663 read_parameter_file( const char *fname
)
2665 static struct { const char *name
;
2668 { "Key-Type", pKEYTYPE
},
2669 { "Key-Length", pKEYLENGTH
},
2670 { "Key-Usage", pKEYUSAGE
},
2671 { "Subkey-Type", pSUBKEYTYPE
},
2672 { "Subkey-Length", pSUBKEYLENGTH
},
2673 { "Subkey-Usage", pSUBKEYUSAGE
},
2674 { "Name-Real", pNAMEREAL
},
2675 { "Name-Email", pNAMEEMAIL
},
2676 { "Name-Comment", pNAMECOMMENT
},
2677 { "Expire-Date", pEXPIREDATE
},
2678 { "Creation-Date", pCREATIONDATE
},
2679 { "Passphrase", pPASSPHRASE
},
2680 { "Preferences", pPREFERENCES
},
2681 { "Revoker", pREVOKER
},
2682 { "Handle", pHANDLE
},
2683 { "Keyserver", pKEYSERVER
},
2688 unsigned int maxlen
, nline
;
2691 const char *err
= NULL
;
2692 struct para_data_s
*para
, *r
;
2694 struct output_control_s outctrl
;
2696 memset( &outctrl
, 0, sizeof( outctrl
) );
2697 outctrl
.pub
.afx
= new_armor_context ();
2698 outctrl
.sec
.afx
= new_armor_context ();
2700 if( !fname
|| !*fname
)
2703 fp
= iobuf_open (fname
);
2704 if (fp
&& is_secured_file (iobuf_get_fd (fp
)))
2711 log_error (_("can't open `%s': %s\n"), fname
, strerror(errno
) );
2714 iobuf_ioctl (fp
, 3, 1, NULL
); /* No file caching. */
2721 while ( iobuf_read_line (fp
, &line
, &nline
, &maxlen
) ) {
2722 char *keyword
, *value
;
2726 err
= "line too long";
2729 for( p
= line
; isspace(*(byte
*)p
); p
++ )
2731 if( !*p
|| *p
== '#' )
2734 if( *keyword
== '%' ) {
2735 for( ; !isspace(*(byte
*)p
); p
++ )
2739 for( ; isspace(*(byte
*)p
); p
++ )
2742 trim_trailing_ws( value
, strlen(value
) );
2743 if( !ascii_strcasecmp( keyword
, "%echo" ) )
2744 log_info("%s\n", value
);
2745 else if( !ascii_strcasecmp( keyword
, "%dry-run" ) )
2747 else if( !ascii_strcasecmp( keyword
, "%ask-passphrase" ) )
2748 outctrl
.ask_passphrase
= 1;
2749 else if( !ascii_strcasecmp( keyword
, "%no-ask-passphrase" ) )
2750 outctrl
.ask_passphrase
= 0;
2751 else if( !ascii_strcasecmp( keyword
, "%commit" ) ) {
2753 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2754 print_status_key_not_created
2755 (get_parameter_value (para
, pHANDLE
));
2756 release_parameter_list( para
);
2759 else if( !ascii_strcasecmp( keyword
, "%pubring" ) ) {
2760 if( outctrl
.pub
.fname
&& !strcmp( outctrl
.pub
.fname
, value
) )
2761 ; /* still the same file - ignore it */
2763 xfree( outctrl
.pub
.newfname
);
2764 outctrl
.pub
.newfname
= xstrdup( value
);
2765 outctrl
.use_files
= 1;
2768 else if( !ascii_strcasecmp( keyword
, "%secring" ) ) {
2769 if( outctrl
.sec
.fname
&& !strcmp( outctrl
.sec
.fname
, value
) )
2770 ; /* still the same file - ignore it */
2772 xfree( outctrl
.sec
.newfname
);
2773 outctrl
.sec
.newfname
= xstrdup( value
);
2774 outctrl
.use_files
= 1;
2778 log_info("skipping control `%s' (%s)\n", keyword
, value
);
2785 if( !(p
= strchr( p
, ':' )) || p
== keyword
) {
2786 err
= "missing colon";
2791 for( ; isspace(*(byte
*)p
); p
++ )
2794 err
= "missing argument";
2798 trim_trailing_ws( value
, strlen(value
) );
2800 for(i
=0; keywords
[i
].name
; i
++ ) {
2801 if( !ascii_strcasecmp( keywords
[i
].name
, keyword
) )
2804 if( !keywords
[i
].name
) {
2805 err
= "unknown keyword";
2808 if( keywords
[i
].key
!= pKEYTYPE
&& !para
) {
2809 err
= "parameter block does not start with \"Key-Type\"";
2813 if( keywords
[i
].key
== pKEYTYPE
&& para
) {
2815 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2816 print_status_key_not_created
2817 (get_parameter_value (para
, pHANDLE
));
2818 release_parameter_list( para
);
2822 for( r
= para
; r
; r
= r
->next
) {
2823 if( r
->key
== keywords
[i
].key
)
2827 err
= "duplicate keyword";
2831 r
= xmalloc_clear( sizeof *r
+ strlen( value
) );
2833 r
->key
= keywords
[i
].key
;
2834 strcpy( r
->u
.value
, value
);
2839 log_error("%s:%d: %s\n", fname
, lnr
, err
);
2840 else if( iobuf_error (fp
) ) {
2841 log_error("%s:%d: read error\n", fname
, lnr
);
2845 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2846 print_status_key_not_created (get_parameter_value (para
, pHANDLE
));
2849 if( outctrl
.use_files
) { /* close open streams */
2850 iobuf_close( outctrl
.pub
.stream
);
2851 iobuf_close( outctrl
.sec
.stream
);
2853 /* Must invalidate that ugly cache to actually close it. */
2854 if (outctrl
.pub
.fname
)
2855 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.pub
.fname
);
2856 if (outctrl
.sec
.fname
)
2857 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.sec
.fname
);
2859 xfree( outctrl
.pub
.fname
);
2860 xfree( outctrl
.pub
.newfname
);
2861 xfree( outctrl
.sec
.fname
);
2862 xfree( outctrl
.sec
.newfname
);
2865 release_parameter_list( para
);
2867 release_armor_context (outctrl
.pub
.afx
);
2868 release_armor_context (outctrl
.sec
.afx
);
2873 * Generate a keypair (fname is only used in batch mode) If
2874 * CARD_SERIALNO is not NULL the function will create the keys on an
2875 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2876 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2877 * generate in software, imported to the card and a backup file
2878 * written to directory given by this argument .
2881 generate_keypair (const char *fname
, const char *card_serialno
,
2882 const char *backup_encryption_dir
)
2892 struct para_data_s
*para
= NULL
;
2893 struct para_data_s
*r
;
2894 struct output_control_s outctrl
;
2897 memset( &outctrl
, 0, sizeof( outctrl
) );
2899 if (opt
.batch
&& card_serialno
)
2901 /* We don't yet support unattended key generation. */
2902 log_error (_("can't do this in batch mode\n"));
2908 read_parameter_file( fname
);
2914 #ifdef ENABLE_CARD_SUPPORT
2915 r
= xcalloc (1, sizeof *r
+ strlen (card_serialno
) );
2917 strcpy( r
->u
.value
, card_serialno
);
2921 algo
= PUBKEY_ALGO_RSA
;
2923 r
= xcalloc (1, sizeof *r
+ 20 );
2925 sprintf( r
->u
.value
, "%d", algo
);
2928 r
= xcalloc (1, sizeof *r
+ 20 );
2930 strcpy (r
->u
.value
, "sign");
2934 r
= xcalloc (1, sizeof *r
+ 20 );
2935 r
->key
= pSUBKEYTYPE
;
2936 sprintf( r
->u
.value
, "%d", algo
);
2939 r
= xcalloc (1, sizeof *r
+ 20 );
2940 r
->key
= pSUBKEYUSAGE
;
2941 strcpy (r
->u
.value
, "encrypt");
2945 r
= xcalloc (1, sizeof *r
+ 20 );
2946 r
->key
= pAUTHKEYTYPE
;
2947 sprintf( r
->u
.value
, "%d", algo
);
2951 if (backup_encryption_dir
)
2953 r
= xcalloc (1, sizeof *r
+ strlen (backup_encryption_dir
) );
2954 r
->key
= pBACKUPENCDIR
;
2955 strcpy (r
->u
.value
, backup_encryption_dir
);
2959 #endif /*ENABLE_CARD_SUPPORT*/
2963 algo
= ask_algo( 0, &use
);
2965 { /* default: DSA with ElG subkey of the specified size */
2967 r
= xmalloc_clear( sizeof *r
+ 20 );
2969 sprintf( r
->u
.value
, "%d", PUBKEY_ALGO_DSA
);
2972 nbits
= ask_keysize( PUBKEY_ALGO_DSA
);
2973 r
= xmalloc_clear( sizeof *r
+ 20 );
2974 r
->key
= pKEYLENGTH
;
2975 sprintf( r
->u
.value
, "%u", nbits
);
2978 r
= xmalloc_clear( sizeof *r
+ 20 );
2980 strcpy( r
->u
.value
, "sign" );
2984 algo
= PUBKEY_ALGO_ELGAMAL_E
;
2985 r
= xmalloc_clear( sizeof *r
+ 20 );
2986 r
->key
= pSUBKEYTYPE
;
2987 sprintf( r
->u
.value
, "%d", algo
);
2990 r
= xmalloc_clear( sizeof *r
+ 20 );
2991 r
->key
= pSUBKEYUSAGE
;
2992 strcpy( r
->u
.value
, "encrypt" );
2998 r
= xmalloc_clear( sizeof *r
+ 20 );
3000 sprintf( r
->u
.value
, "%d", algo
);
3006 r
= xmalloc_clear( sizeof *r
+ 25 );
3008 sprintf( r
->u
.value
, "%s%s%s",
3009 (use
& PUBKEY_USAGE_SIG
)? "sign ":"",
3010 (use
& PUBKEY_USAGE_ENC
)? "encrypt ":"",
3011 (use
& PUBKEY_USAGE_AUTH
)? "auth":"" );
3018 nbits
= ask_keysize( algo
);
3019 r
= xmalloc_clear( sizeof *r
+ 20 );
3020 r
->key
= both
? pSUBKEYLENGTH
: pKEYLENGTH
;
3021 sprintf( r
->u
.value
, "%u", nbits
);
3026 expire
= ask_expire_interval(0,NULL
);
3027 r
= xmalloc_clear( sizeof *r
+ 20 );
3028 r
->key
= pKEYEXPIRE
;
3029 r
->u
.expire
= expire
;
3032 r
= xmalloc_clear( sizeof *r
+ 20 );
3033 r
->key
= pSUBKEYEXPIRE
;
3034 r
->u
.expire
= expire
;
3038 uid
= ask_user_id(0);
3041 log_error(_("Key generation canceled.\n"));
3042 release_parameter_list( para
);
3045 r
= xmalloc_clear( sizeof *r
+ strlen(uid
) );
3047 strcpy( r
->u
.value
, uid
);
3052 dek
= card_serialno
? NULL
: do_ask_passphrase ( &s2k
, &canceled
);
3055 r
= xmalloc_clear( sizeof *r
);
3056 r
->key
= pPASSPHRASE_DEK
;
3060 r
= xmalloc_clear( sizeof *r
);
3061 r
->key
= pPASSPHRASE_S2K
;
3068 log_error (_("Key generation canceled.\n"));
3070 proc_parameter_file( para
, "[internal]", &outctrl
, !!card_serialno
);
3071 release_parameter_list( para
);
3075 #ifdef ENABLE_CARD_SUPPORT
3076 /* Generate a raw key and return it as a secret key packet. The
3077 function will ask for the passphrase and return a protected as well
3078 as an unprotected copy of a new secret key packet. 0 is returned
3079 on success and the caller must then free the returned values. */
3081 generate_raw_key (int algo
, unsigned int nbits
, u32 created_at
,
3082 PKT_secret_key
**r_sk_unprotected
,
3083 PKT_secret_key
**r_sk_protected
)
3087 STRING2KEY
*s2k
= NULL
;
3088 PKT_secret_key
*sk
= NULL
;
3090 size_t nskey
, npkey
;
3091 gcry_sexp_t s_parms
, s_key
;
3094 npkey
= pubkey_get_npkey (algo
);
3095 nskey
= pubkey_get_nskey (algo
);
3096 assert (nskey
<= PUBKEY_MAX_NSKEY
&& npkey
< nskey
);
3101 log_info (_("keysize invalid; using %u bits\n"), nbits
);
3106 nbits
= ((nbits
+ 31) / 32) * 32;
3107 log_info(_("keysize rounded up to %u bits\n"), nbits
);
3110 dek
= do_ask_passphrase (&s2k
, &canceled
);
3113 rc
= gpg_error (GPG_ERR_CANCELED
);
3117 sk
= xmalloc_clear (sizeof *sk
);
3118 sk
->timestamp
= created_at
;
3120 sk
->pubkey_algo
= algo
;
3122 if ( !is_RSA (algo
) )
3124 log_error ("only RSA is supported for offline generated keys\n");
3125 rc
= gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
3128 rc
= gcry_sexp_build (&s_parms
, NULL
,
3129 "(genkey(rsa(nbits %d)))",
3132 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
3133 rc
= gcry_pk_genkey (&s_key
, s_parms
);
3134 gcry_sexp_release (s_parms
);
3137 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
3140 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
3141 gcry_sexp_release (s_key
);
3144 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
3148 for (i
=npkey
; i
< nskey
; i
++)
3149 sk
->csum
+= checksum_mpi (sk
->skey
[i
]);
3151 if (r_sk_unprotected
)
3152 *r_sk_unprotected
= copy_secret_key (NULL
, sk
);
3154 rc
= genhelp_protect (dek
, s2k
, sk
);
3160 *r_sk_protected
= sk
;
3166 free_secret_key (sk
);
3171 #endif /* ENABLE_CARD_SUPPORT */
3173 /* Create and delete a dummy packet to start off a list of kbnodes. */
3175 start_tree(KBNODE
*tree
)
3179 pkt
=xmalloc_clear(sizeof(*pkt
));
3180 pkt
->pkttype
=PKT_NONE
;
3181 *tree
=new_kbnode(pkt
);
3182 delete_kbnode(*tree
);
3187 do_generate_keypair (struct para_data_s
*para
,
3188 struct output_control_s
*outctrl
, int card
)
3190 KBNODE pub_root
= NULL
;
3191 KBNODE sec_root
= NULL
;
3192 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3194 struct revocation_key
*revkey
;
3199 if( outctrl
->dryrun
)
3201 log_info("dry-run mode - key generation skipped\n");
3205 if ( outctrl
->use_files
)
3207 if ( outctrl
->pub
.newfname
)
3209 iobuf_close(outctrl
->pub
.stream
);
3210 outctrl
->pub
.stream
= NULL
;
3211 if (outctrl
->pub
.fname
)
3212 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->pub
.fname
);
3213 xfree( outctrl
->pub
.fname
);
3214 outctrl
->pub
.fname
= outctrl
->pub
.newfname
;
3215 outctrl
->pub
.newfname
= NULL
;
3217 if (is_secured_filename (outctrl
->pub
.fname
) )
3219 outctrl
->pub
.stream
= NULL
;
3223 outctrl
->pub
.stream
= iobuf_create( outctrl
->pub
.fname
);
3224 if (!outctrl
->pub
.stream
)
3226 log_error(_("can't create `%s': %s\n"), outctrl
->pub
.newfname
,
3232 outctrl
->pub
.afx
->what
= 1;
3233 push_armor_filter (outctrl
->pub
.afx
, outctrl
->pub
.stream
);
3236 if (outctrl
->sec
.newfname
)
3240 iobuf_close(outctrl
->sec
.stream
);
3241 outctrl
->sec
.stream
= NULL
;
3242 if (outctrl
->sec
.fname
)
3243 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->sec
.fname
);
3244 xfree( outctrl
->sec
.fname
);
3245 outctrl
->sec
.fname
= outctrl
->sec
.newfname
;
3246 outctrl
->sec
.newfname
= NULL
;
3248 oldmask
= umask (077);
3249 if (is_secured_filename (outctrl
->sec
.fname
) )
3251 outctrl
->sec
.stream
= NULL
;
3255 outctrl
->sec
.stream
= iobuf_create( outctrl
->sec
.fname
);
3257 if (!outctrl
->sec
.stream
)
3259 log_error(_("can't create `%s': %s\n"), outctrl
->sec
.newfname
,
3265 outctrl
->sec
.afx
->what
= 5;
3266 push_armor_filter (outctrl
->sec
.afx
, outctrl
->sec
.stream
);
3269 assert( outctrl
->pub
.stream
);
3270 assert( outctrl
->sec
.stream
);
3273 log_info (_("writing public key to `%s'\n"), outctrl
->pub
.fname
);
3275 log_info (_("writing secret key stub to `%s'\n"),
3276 outctrl
->sec
.fname
);
3278 log_info(_("writing secret key to `%s'\n"), outctrl
->sec
.fname
);
3283 /* We create the packets as a tree of kbnodes. Because the
3284 structure we create is known in advance we simply generate a
3285 linked list. The first packet is a dummy packet which we flag as
3286 deleted. The very first packet must always be a KEY packet. */
3288 start_tree (&pub_root
);
3289 start_tree (&sec_root
);
3291 timestamp
= get_parameter_u32 (para
, pKEYCREATIONDATE
);
3293 timestamp
= make_timestamp ();
3297 rc
= do_create (get_parameter_algo( para
, pKEYTYPE
),
3298 get_parameter_uint( para
, pKEYLENGTH
),
3300 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3301 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3304 get_parameter_u32( para
, pKEYEXPIRE
), 0 );
3308 /* Note, that depending on the backend, the card key generation
3309 may update TIMESTAMP. */
3310 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 1, 1, pub_root
, sec_root
, NULL
,
3312 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3315 pri_sk
= sec_root
->next
->pkt
->pkt
.secret_key
;
3320 if(!rc
&& (revkey
=get_parameter_revkey(para
,pREVOKER
)))
3322 rc
= write_direct_sig (pub_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3324 rc
= write_direct_sig (sec_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3327 if( !rc
&& (s
=get_parameter_value(para
, pUSERID
)) )
3329 write_uid (pub_root
, s
);
3330 write_uid (sec_root
, s
);
3332 rc
= write_selfsigs (sec_root
, pub_root
, pri_sk
,
3333 get_parameter_uint (para
, pKEYUSAGE
), timestamp
);
3336 /* Write the auth key to the card before the encryption key. This
3337 is a partial workaround for a PGP bug (as of this writing, all
3338 versions including 8.1), that causes it to try and encrypt to
3339 the most recent subkey regardless of whether that subkey is
3340 actually an encryption type. In this case, the auth key is an
3341 RSA key so it succeeds. */
3343 if (!rc
&& card
&& get_parameter (para
, pAUTHKEYTYPE
))
3345 /* Note, that depending on the backend, the card key generation
3346 may update TIMESTAMP. */
3347 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 3, 0, pub_root
, sec_root
, NULL
,
3349 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3352 rc
= write_keybinding (pub_root
, pub_root
, pri_sk
, sub_sk
,
3353 PUBKEY_USAGE_AUTH
, timestamp
);
3355 rc
= write_keybinding (sec_root
, pub_root
, pri_sk
, sub_sk
,
3356 PUBKEY_USAGE_AUTH
, timestamp
);
3359 if( !rc
&& get_parameter( para
, pSUBKEYTYPE
) )
3363 rc
= do_create( get_parameter_algo( para
, pSUBKEYTYPE
),
3364 get_parameter_uint( para
, pSUBKEYLENGTH
),
3366 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3367 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3370 get_parameter_u32( para
, pSUBKEYEXPIRE
), 1 );
3374 if ((s
= get_parameter_value (para
, pBACKUPENCDIR
)))
3376 /* A backup of the encryption key has been requested.
3377 Generate the key in software and import it then to
3378 the card. Write a backup file. */
3379 rc
= gen_card_key_with_backup (PUBKEY_ALGO_RSA
, 2, 0,
3382 get_parameter_u32 (para
,
3388 /* Note, that depending on the backend, the card key
3389 generation may update TIMESTAMP. */
3390 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 2, 0, pub_root
, sec_root
,
3393 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3398 rc
= write_keybinding(pub_root
, pub_root
, pri_sk
, sub_sk
,
3399 get_parameter_uint (para
, pSUBKEYUSAGE
),
3402 rc
= write_keybinding(sec_root
, pub_root
, pri_sk
, sub_sk
,
3403 get_parameter_uint (para
, pSUBKEYUSAGE
),
3408 if (!rc
&& outctrl
->use_files
) /* Direct write to specified files. */
3410 rc
= write_keyblock( outctrl
->pub
.stream
, pub_root
);
3412 log_error ("can't write public key: %s\n", g10_errstr(rc
) );
3415 rc
= write_keyblock( outctrl
->sec
.stream
, sec_root
);
3417 log_error ("can't write secret key: %s\n", g10_errstr(rc
) );
3420 else if (!rc
) /* Write to the standard keyrings. */
3422 KEYDB_HANDLE pub_hd
= keydb_new (0);
3423 KEYDB_HANDLE sec_hd
= keydb_new (1);
3425 rc
= keydb_locate_writable (pub_hd
, NULL
);
3427 log_error (_("no writable public keyring found: %s\n"),
3432 rc
= keydb_locate_writable (sec_hd
, NULL
);
3434 log_error (_("no writable secret keyring found: %s\n"),
3438 if (!rc
&& opt
.verbose
)
3440 log_info (_("writing public key to `%s'\n"),
3441 keydb_get_resource_name (pub_hd
));
3443 log_info (_("writing secret key stub to `%s'\n"),
3444 keydb_get_resource_name (sec_hd
));
3446 log_info (_("writing secret key to `%s'\n"),
3447 keydb_get_resource_name (sec_hd
));
3452 rc
= keydb_insert_keyblock (pub_hd
, pub_root
);
3454 log_error (_("error writing public keyring `%s': %s\n"),
3455 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3460 rc
= keydb_insert_keyblock (sec_hd
, sec_root
);
3462 log_error (_("error writing secret keyring `%s': %s\n"),
3463 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3466 keydb_release (pub_hd
);
3467 keydb_release (sec_hd
);
3474 no_enc_rsa
= (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_RSA
3475 && get_parameter_uint (para
, pKEYUSAGE
)
3476 && !((get_parameter_uint (para
, pKEYUSAGE
)
3477 & PUBKEY_USAGE_ENC
)) );
3479 pk
= find_kbnode (pub_root
, PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3481 keyid_from_pk(pk
,pk
->main_keyid
);
3482 register_trusted_keyid(pk
->main_keyid
);
3484 update_ownertrust (pk
, ((get_ownertrust (pk
) & ~TRUST_MASK
)
3485 | TRUST_ULTIMATE
));
3489 tty_printf (_("public and secret key created and signed.\n") );
3491 list_keyblock(pub_root
,0,1,NULL
);
3496 && (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_DSA
3498 && !get_parameter (para
, pSUBKEYTYPE
) )
3500 tty_printf(_("Note that this key cannot be used for "
3501 "encryption. You may want to use\n"
3502 "the command \"--edit-key\" to generate a "
3503 "subkey for this purpose.\n") );
3511 log_error ("key generation failed: %s\n", g10_errstr(rc
) );
3513 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3514 print_status_key_not_created ( get_parameter_value (para
, pHANDLE
) );
3518 PKT_public_key
*pk
= find_kbnode (pub_root
,
3519 PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3520 print_status_key_created (did_sub
? 'B':'P', pk
,
3521 get_parameter_value (para
, pHANDLE
));
3523 release_kbnode( pub_root
);
3524 release_kbnode( sec_root
);
3526 if (pri_sk
&& !card
) /* The unprotected secret key unless we */
3527 free_secret_key (pri_sk
); /* have a shallow copy in card mode. */
3529 free_secret_key(sub_sk
);
3533 /* Add a new subkey to an existing key. Returns true if a new key has
3534 been generated and put into the keyblocks. */
3536 generate_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
)
3540 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3545 char *passphrase
= NULL
;
3547 STRING2KEY
*s2k
= NULL
;
3552 /* Break out the primary secret key. */
3553 node
= find_kbnode( sec_keyblock
, PKT_SECRET_KEY
);
3556 log_error ("Oops; secret key not found anymore!\n");
3560 /* Make a copy of the sk to keep the protected one in the keyblock. */
3561 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3563 cur_time
= make_timestamp();
3565 if (pri_sk
->timestamp
> cur_time
)
3567 ulong d
= pri_sk
->timestamp
- cur_time
;
3568 log_info ( d
==1 ? _("key has been created %lu second "
3569 "in future (time warp or clock problem)\n")
3570 : _("key has been created %lu seconds "
3571 "in future (time warp or clock problem)\n"), d
);
3572 if (!opt
.ignore_time_conflict
)
3574 rc
= G10ERR_TIME_CONFLICT
;
3579 if (pri_sk
->version
< 4)
3581 log_info (_("NOTE: creating subkeys for v3 keys "
3582 "is not OpenPGP compliant\n"));
3586 if (pri_sk
->is_protected
&& pri_sk
->protect
.s2k
.mode
== 1001)
3588 tty_printf (_("Secret parts of primary key are not available.\n"));
3589 rc
= G10ERR_NO_SECKEY
;
3594 /* Unprotect to get the passphrase. */
3595 switch (is_secret_key_protected (pri_sk
) )
3598 rc
= G10ERR_PUBKEY_ALGO
;
3601 tty_printf (_("This key is not protected.\n"));
3604 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3608 tty_printf (_("Key is protected.\n"));
3609 rc
= check_secret_key ( pri_sk
, 0 );
3611 passphrase
= get_last_passphrase();
3617 algo
= ask_algo (1, &use
);
3619 nbits
= ask_keysize (algo
);
3620 expire
= ask_expire_interval (0, NULL
);
3621 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3622 _("Really create? (y/N) ")))
3627 dek
= do_ask_passphrase (&s2k
, &canceled
);
3628 else if (passphrase
)
3630 s2k
= xmalloc_secure ( sizeof *s2k
);
3631 s2k
->mode
= opt
.s2k_mode
;
3632 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
3633 set_next_passphrase ( passphrase
);
3634 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
3639 rc
= GPG_ERR_CANCELED
;
3642 rc
= do_create (algo
, nbits
, pub_keyblock
, sec_keyblock
,
3643 dek
, s2k
, &sub_sk
, cur_time
, expire
, 1 );
3645 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3648 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3653 write_status_text (STATUS_KEY_CREATED
, "S");
3658 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3662 /* Release the copy of the (now unprotected) secret keys. */
3664 free_secret_key (pri_sk
);
3666 free_secret_key (sub_sk
);
3667 set_next_passphrase (NULL
);
3672 #ifdef ENABLE_CARD_SUPPORT
3673 /* Generate a subkey on a card. */
3675 generate_card_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
,
3676 int keyno
, const char *serialno
)
3680 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
;
3684 char *passphrase
= NULL
;
3686 struct para_data_s
*para
= NULL
;
3688 assert (keyno
>= 1 && keyno
<= 3);
3690 para
= xcalloc (1, sizeof *para
+ strlen (serialno
) );
3691 para
->key
= pSERIALNO
;
3692 strcpy (para
->u
.value
, serialno
);
3694 /* Break out the primary secret key */
3695 node
= find_kbnode (sec_keyblock
, PKT_SECRET_KEY
);
3698 log_error("Oops; secret key not found anymore!\n");
3702 /* Make a copy of the sk to keep the protected one in the keyblock */
3703 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3705 cur_time
= make_timestamp();
3706 if (pri_sk
->timestamp
> cur_time
)
3708 ulong d
= pri_sk
->timestamp
- cur_time
;
3709 log_info (d
==1 ? _("key has been created %lu second "
3710 "in future (time warp or clock problem)\n")
3711 : _("key has been created %lu seconds "
3712 "in future (time warp or clock problem)\n"), d
);
3713 if (!opt
.ignore_time_conflict
)
3715 rc
= G10ERR_TIME_CONFLICT
;
3720 if (pri_sk
->version
< 4)
3722 log_info (_("NOTE: creating subkeys for v3 keys "
3723 "is not OpenPGP compliant\n"));
3727 /* Unprotect to get the passphrase. */
3728 switch( is_secret_key_protected (pri_sk
) )
3731 rc
= G10ERR_PUBKEY_ALGO
;
3734 tty_printf("This key is not protected.\n");
3737 tty_printf("Key is protected.\n");
3738 rc
= check_secret_key( pri_sk
, 0 );
3740 passphrase
= get_last_passphrase();
3746 algo
= PUBKEY_ALGO_RSA
;
3747 expire
= ask_expire_interval (0,NULL
);
3749 use
= PUBKEY_USAGE_SIG
;
3750 else if (keyno
== 2)
3751 use
= PUBKEY_USAGE_ENC
;
3753 use
= PUBKEY_USAGE_AUTH
;
3754 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3755 _("Really create? (y/N) ")))
3759 set_next_passphrase (passphrase
);
3761 /* Note, that depending on the backend, the card key generation may
3763 rc
= gen_card_key (algo
, keyno
, 0, pub_keyblock
, sec_keyblock
,
3764 &sub_sk
, &cur_time
, expire
, para
);
3766 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3769 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3774 write_status_text (STATUS_KEY_CREATED
, "S");
3779 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3781 /* Release the copy of the (now unprotected) secret keys. */
3783 free_secret_key (pri_sk
);
3784 set_next_passphrase( NULL
);
3785 release_parameter_list (para
);
3788 #endif /* !ENABLE_CARD_SUPPORT */
3792 * Write a keyblock to an output stream
3795 write_keyblock( IOBUF out
, KBNODE node
)
3797 for( ; node
; node
= node
->next
)
3799 if(!is_deleted_kbnode(node
))
3801 int rc
= build_packet( out
, node
->pkt
);
3804 log_error("build_packet(%d) failed: %s\n",
3805 node
->pkt
->pkttype
, g10_errstr(rc
) );
3815 /* Note that timestamp is an in/out arg. */
3817 gen_card_key (int algo
, int keyno
, int is_primary
,
3818 KBNODE pub_root
, KBNODE sec_root
, PKT_secret_key
**ret_sk
,
3819 u32
*timestamp
, u32 expireval
, struct para_data_s
*para
)
3821 #ifdef ENABLE_CARD_SUPPORT
3824 struct agent_card_genkey_s info
;
3829 assert (algo
== PUBKEY_ALGO_RSA
);
3831 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3832 rc
= agent_scd_genkey (&info
, keyno
, 1, NULL
, *timestamp
);
3833 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3835 /* tty_printf ("\n"); */
3836 /* log_error ("WARNING: key does already exists!\n"); */
3837 /* tty_printf ("\n"); */
3838 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3839 /* _("Replace existing key? "))) */
3840 /* rc = agent_scd_genkey (&info, keyno, 1); */
3845 log_error ("key generation failed: %s\n", gpg_strerror (rc
));
3848 if ( !info
.n
|| !info
.e
)
3850 log_error ("communication error with SCD\n");
3851 gcry_mpi_release (info
.n
);
3852 gcry_mpi_release (info
.e
);
3853 return gpg_error (GPG_ERR_GENERAL
);
3856 if (*timestamp
!= info
.created_at
)
3857 log_info ("Note that the key does not use the suggested creation date\n");
3858 *timestamp
= info
.created_at
;
3860 pk
= xcalloc (1, sizeof *pk
);
3861 sk
= xcalloc (1, sizeof *sk
);
3862 sk
->timestamp
= pk
->timestamp
= info
.created_at
;
3863 sk
->version
= pk
->version
= 4;
3865 sk
->expiredate
= pk
->expiredate
= pk
->timestamp
+ expireval
;
3866 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
3867 pk
->pkey
[0] = info
.n
;
3868 pk
->pkey
[1] = info
.e
;
3869 sk
->skey
[0] = gcry_mpi_copy (pk
->pkey
[0]);
3870 sk
->skey
[1] = gcry_mpi_copy (pk
->pkey
[1]);
3871 sk
->skey
[2] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3872 sk
->is_protected
= 1;
3873 sk
->protect
.s2k
.mode
= 1002;
3874 s
= get_parameter_value (para
, pSERIALNO
);
3877 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
3878 sk
->protect
.ivlen
++, s
+= 2)
3879 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
3885 pkt
= xcalloc (1,sizeof *pkt
);
3886 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
3887 pkt
->pkt
.public_key
= pk
;
3888 add_kbnode(pub_root
, new_kbnode( pkt
));
3890 pkt
= xcalloc (1,sizeof *pkt
);
3891 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
3892 pkt
->pkt
.secret_key
= sk
;
3893 add_kbnode(sec_root
, new_kbnode( pkt
));
3898 #endif /*!ENABLE_CARD_SUPPORT*/
3904 gen_card_key_with_backup (int algo
, int keyno
, int is_primary
,
3905 KBNODE pub_root
, KBNODE sec_root
,
3907 u32 expireval
, struct para_data_s
*para
,
3908 const char *backup_dir
)
3910 #ifdef ENABLE_CARD_SUPPORT
3914 PKT_secret_key
*sk
, *sk_unprotected
= NULL
, *sk_protected
= NULL
;
3919 rc
= generate_raw_key (algo
, 1024, timestamp
,
3920 &sk_unprotected
, &sk_protected
);
3924 /* First, store the key to the card. */
3925 rc
= save_unprotected_key_to_card (sk_unprotected
, keyno
);
3928 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc
));
3929 free_secret_key (sk_unprotected
);
3930 free_secret_key (sk_protected
);
3934 /* Get rid of the secret key parameters and store the serial numer. */
3935 sk
= sk_unprotected
;
3936 n
= pubkey_get_nskey (sk
->pubkey_algo
);
3937 for (i
=pubkey_get_npkey (sk
->pubkey_algo
); i
< n
; i
++)
3939 gcry_mpi_release (sk
->skey
[i
]);
3942 i
= pubkey_get_npkey (sk
->pubkey_algo
);
3943 sk
->skey
[i
] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3944 sk
->is_protected
= 1;
3945 sk
->protect
.s2k
.mode
= 1002;
3946 s
= get_parameter_value (para
, pSERIALNO
);
3948 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
3949 sk
->protect
.ivlen
++, s
+= 2)
3950 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
3952 /* Now write the *protected* secret key to the file. */
3954 char name_buffer
[50];
3959 keyid_from_sk (sk
, NULL
);
3960 sprintf (name_buffer
,"sk_%08lX%08lX.gpg",
3961 (ulong
)sk
->keyid
[0], (ulong
)sk
->keyid
[1]);
3963 fname
= make_filename (backup_dir
, name_buffer
, NULL
);
3964 oldmask
= umask (077);
3965 if (is_secured_filename (fname
))
3971 fp
= iobuf_create (fname
);
3975 rc
= gpg_error_from_syserror ();
3976 log_error (_("can't create backup file `%s': %s\n"),
3977 fname
, strerror(errno
) );
3979 free_secret_key (sk_unprotected
);
3980 free_secret_key (sk_protected
);
3984 pkt
= xcalloc (1, sizeof *pkt
);
3985 pkt
->pkttype
= PKT_SECRET_KEY
;
3986 pkt
->pkt
.secret_key
= sk_protected
;
3987 sk_protected
= NULL
;
3989 rc
= build_packet (fp
, pkt
);
3992 log_error("build packet failed: %s\n", g10_errstr(rc
) );
3997 unsigned char array
[MAX_FINGERPRINT_LEN
];
4001 iobuf_ioctl (NULL
, 2, 0, (char*)fname
);
4002 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname
);
4004 fingerprint_from_sk (sk
, array
, &n
);
4005 p
= fprbuf
= xmalloc (MAX_FINGERPRINT_LEN
*2 + 1 + 1);
4006 for (i
=0; i
< n
; i
++, p
+= 2)
4007 sprintf (p
, "%02X", array
[i
]);
4011 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED
,
4013 fname
, strlen (fname
),
4022 free_secret_key (sk_unprotected
);
4027 /* Create the public key from the secret key. */
4028 pk
= xcalloc (1, sizeof *pk
);
4029 pk
->timestamp
= sk
->timestamp
;
4030 pk
->version
= sk
->version
;
4032 pk
->expiredate
= sk
->expiredate
= sk
->timestamp
+ expireval
;
4033 pk
->pubkey_algo
= sk
->pubkey_algo
;
4034 n
= pubkey_get_npkey (sk
->pubkey_algo
);
4035 for (i
=0; i
< n
; i
++)
4036 pk
->pkey
[i
] = mpi_copy (sk
->skey
[i
]);
4038 /* Build packets and add them to the node lists. */
4039 pkt
= xcalloc (1,sizeof *pkt
);
4040 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
4041 pkt
->pkt
.public_key
= pk
;
4042 add_kbnode(pub_root
, new_kbnode( pkt
));
4044 pkt
= xcalloc (1,sizeof *pkt
);
4045 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
4046 pkt
->pkt
.secret_key
= sk
;
4047 add_kbnode(sec_root
, new_kbnode( pkt
));
4052 #endif /*!ENABLE_CARD_SUPPORT*/
4056 #ifdef ENABLE_CARD_SUPPORT
4058 save_unprotected_key_to_card (PKT_secret_key
*sk
, int keyno
)
4061 unsigned char *rsa_n
= NULL
;
4062 unsigned char *rsa_e
= NULL
;
4063 unsigned char *rsa_p
= NULL
;
4064 unsigned char *rsa_q
= NULL
;
4065 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
4066 unsigned char *sexp
= NULL
;
4068 char numbuf
[55], numbuf2
[50];
4070 assert (is_RSA (sk
->pubkey_algo
));
4071 assert (!sk
->is_protected
);
4073 /* Copy the parameters into straight buffers. */
4074 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_n
, &rsa_n_len
, sk
->skey
[0]);
4075 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_e
, &rsa_e_len
, sk
->skey
[1]);
4076 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_p
, &rsa_p_len
, sk
->skey
[3]);
4077 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_q
, &rsa_q_len
, sk
->skey
[4]);
4078 if (!rsa_n
|| !rsa_e
|| !rsa_p
|| !rsa_q
)
4080 rc
= G10ERR_INV_ARG
;
4084 /* Put the key into an S-expression. */
4085 sexp
= p
= xmalloc_secure (30
4086 + rsa_n_len
+ rsa_e_len
+ rsa_p_len
+ rsa_q_len
4087 + 4*sizeof (numbuf
) + 25 + sizeof(numbuf
) + 20);
4089 p
= stpcpy (p
,"(11:private-key(3:rsa(1:n");
4090 sprintf (numbuf
, "%u:", (unsigned int)rsa_n_len
);
4091 p
= stpcpy (p
, numbuf
);
4092 memcpy (p
, rsa_n
, rsa_n_len
);
4095 sprintf (numbuf
, ")(1:e%u:", (unsigned int)rsa_e_len
);
4096 p
= stpcpy (p
, numbuf
);
4097 memcpy (p
, rsa_e
, rsa_e_len
);
4100 sprintf (numbuf
, ")(1:p%u:", (unsigned int)rsa_p_len
);
4101 p
= stpcpy (p
, numbuf
);
4102 memcpy (p
, rsa_p
, rsa_p_len
);
4105 sprintf (numbuf
, ")(1:q%u:", (unsigned int)rsa_q_len
);
4106 p
= stpcpy (p
, numbuf
);
4107 memcpy (p
, rsa_q
, rsa_q_len
);
4110 p
= stpcpy (p
,"))(10:created-at");
4111 sprintf (numbuf2
, "%lu", (unsigned long)sk
->timestamp
);
4112 sprintf (numbuf
, "%lu:", (unsigned long)strlen (numbuf2
));
4113 p
= stpcpy (stpcpy (stpcpy (p
, numbuf
), numbuf2
), "))");
4115 /* Fixme: Unfortunately we don't have the serialnumber available -
4116 thus we can't pass it down to the agent. */
4117 rc
= agent_scd_writekey (keyno
, NULL
, sexp
, p
- sexp
);
4127 #endif /*ENABLE_CARD_SUPPORT*/