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
{
100 armor_filter_context_t
*afx
;
106 armor_filter_context_t
*afx
;
111 struct opaque_data_usage_and_pk
{
117 static int prefs_initialized
= 0;
118 static byte sym_prefs
[MAX_PREFS
];
119 static int nsym_prefs
;
120 static byte hash_prefs
[MAX_PREFS
];
121 static int nhash_prefs
;
122 static byte zip_prefs
[MAX_PREFS
];
123 static int nzip_prefs
;
124 static int mdc_available
,ks_modify
;
126 static void do_generate_keypair( struct para_data_s
*para
,
127 struct output_control_s
*outctrl
, int card
);
128 static int write_keyblock( IOBUF out
, KBNODE node
);
129 static int gen_card_key (int algo
, int keyno
, int is_primary
,
130 KBNODE pub_root
, KBNODE sec_root
,
131 PKT_secret_key
**ret_sk
,
133 u32 expireval
, struct para_data_s
*para
);
134 static int gen_card_key_with_backup (int algo
, int keyno
, int is_primary
,
135 KBNODE pub_root
, KBNODE sec_root
,
137 u32 expireval
, struct para_data_s
*para
,
138 const char *backup_dir
);
142 print_status_key_created (int letter
, PKT_public_key
*pk
, const char *handle
)
144 byte array
[MAX_FINGERPRINT_LEN
], *s
;
151 buf
= xmalloc (MAX_FINGERPRINT_LEN
*2+31 + strlen (handle
) + 1);
158 fingerprint_from_pk (pk
, array
, &n
);
160 for (i
=0; i
< n
; i
++, s
++, p
+= 2)
161 sprintf (p
, "%02X", *s
);
166 for (i
=0; handle
[i
] && i
< 100; i
++)
167 *p
++ = isspace ((unsigned int)handle
[i
])? '_':handle
[i
];
170 write_status_text ((letter
|| pk
)?STATUS_KEY_CREATED
:STATUS_KEY_NOT_CREATED
,
176 print_status_key_not_created (const char *handle
)
178 print_status_key_created (0, NULL
, handle
);
184 write_uid( KBNODE root
, const char *s
)
186 PACKET
*pkt
= xmalloc_clear(sizeof *pkt
);
187 size_t n
= strlen(s
);
189 pkt
->pkttype
= PKT_USER_ID
;
190 pkt
->pkt
.user_id
= xmalloc_clear( sizeof *pkt
->pkt
.user_id
+ n
- 1 );
191 pkt
->pkt
.user_id
->len
= n
;
192 pkt
->pkt
.user_id
->ref
= 1;
193 strcpy(pkt
->pkt
.user_id
->name
, s
);
194 add_kbnode( root
, new_kbnode( pkt
) );
198 do_add_key_flags (PKT_signature
*sig
, unsigned int use
)
204 /* The spec says that all primary keys MUST be able to certify. */
205 if(sig
->sig_class
!=0x18)
208 if (use
& PUBKEY_USAGE_SIG
)
210 if (use
& PUBKEY_USAGE_ENC
)
211 buf
[0] |= 0x04 | 0x08;
212 if (use
& PUBKEY_USAGE_AUTH
)
218 build_sig_subpkt (sig
, SIGSUBPKT_KEY_FLAGS
, buf
, 1);
223 keygen_add_key_expire( PKT_signature
*sig
, void *opaque
)
225 PKT_public_key
*pk
= opaque
;
229 if( pk
->expiredate
) {
230 if(pk
->expiredate
> pk
->timestamp
)
231 u
= pk
->expiredate
- pk
->timestamp
;
235 buf
[0] = (u
>> 24) & 0xff;
236 buf
[1] = (u
>> 16) & 0xff;
237 buf
[2] = (u
>> 8) & 0xff;
239 build_sig_subpkt( sig
, SIGSUBPKT_KEY_EXPIRE
, buf
, 4 );
243 /* Make sure we don't leave a key expiration subpacket lying
245 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_KEY_EXPIRE
);
252 keygen_add_key_flags_and_expire (PKT_signature
*sig
, void *opaque
)
254 struct opaque_data_usage_and_pk
*oduap
= opaque
;
256 do_add_key_flags (sig
, oduap
->usage
);
257 return keygen_add_key_expire (sig
, oduap
->pk
);
261 set_one_pref (int val
, int type
, const char *item
, byte
*buf
, int *nbuf
)
265 for (i
=0; i
< *nbuf
; i
++ )
268 log_info (_("preference `%s' duplicated\n"), item
);
272 if (*nbuf
>= MAX_PREFS
)
275 log_info(_("too many cipher preferences\n"));
277 log_info(_("too many digest preferences\n"));
279 log_info(_("too many compression preferences\n"));
286 buf
[(*nbuf
)++] = val
;
291 * Parse the supplied string and use it to set the standard
292 * preferences. The string may be in a form like the one printed by
293 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
294 * cipher/hash/compress names. Use NULL to set the default
295 * preferences. Returns: 0 = okay
298 keygen_set_std_prefs (const char *string
,int personal
)
300 byte sym
[MAX_PREFS
], hash
[MAX_PREFS
], zip
[MAX_PREFS
];
301 int nsym
=0, nhash
=0, nzip
=0, val
, rc
=0;
302 int mdc
=1, modify
=0; /* mdc defaults on, modify defaults off. */
303 char dummy_string
[45+1]; /* Enough for 15 items. */
305 if (!string
|| !ascii_strcasecmp (string
, "default"))
307 if (opt
.def_preference_list
)
308 string
=opt
.def_preference_list
;
311 dummy_string
[0]='\0';
313 /* The rationale why we use the order AES256,192,128 is
314 for compatibility reasons with PGP. If gpg would
315 define AES128 first, we would get the somewhat
318 gpg -r pgpkey -r gpgkey ---gives--> AES256
319 gpg -r gpgkey -r pgpkey ---gives--> AES
321 Note that by using --personal-cipher-preferences it is
322 possible to prefer AES128.
325 /* Make sure we do not add more than 15 items here, as we
326 could overflow the size of dummy_string. We currently
328 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256
) )
329 strcat(dummy_string
,"S9 ");
330 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192
) )
331 strcat(dummy_string
,"S8 ");
332 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES
) )
333 strcat(dummy_string
,"S7 ");
334 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5
) )
335 strcat(dummy_string
,"S3 ");
336 strcat(dummy_string
,"S2 "); /* 3DES */
337 /* If we have it, IDEA goes *after* 3DES so it won't be
338 used unless we're encrypting along with a V3 key.
339 Ideally, we would only put the S1 preference in if the
340 key was RSA and <=2048 bits, as that is what won't
341 break PGP2, but that is difficult with the current
342 code, and not really worth checking as a non-RSA <=2048
343 bit key wouldn't be usable by PGP2 anyway. -dms */
344 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA
) )
345 strcat(dummy_string
,"S1 ");
348 strcat(dummy_string
,"H2 ");
350 if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256
))
351 strcat(dummy_string
,"H8 ");
354 strcat(dummy_string
,"H3 ");
357 strcat(dummy_string
,"Z2 ");
359 if(!check_compress_algo(COMPRESS_ALGO_BZIP2
))
360 strcat(dummy_string
,"Z3 ");
363 strcat(dummy_string
,"Z1");
368 else if (!ascii_strcasecmp (string
, "none"))
373 char *tok
,*prefstring
;
375 prefstring
=xstrdup(string
); /* need a writable string! */
377 while((tok
=strsep(&prefstring
," ,")))
379 if((val
=string_to_cipher_algo (tok
)))
381 if(set_one_pref(val
,1,tok
,sym
,&nsym
))
384 else if((val
=string_to_digest_algo (tok
)))
386 if(set_one_pref(val
,2,tok
,hash
,&nhash
))
389 else if((val
=string_to_compress_algo(tok
))>-1)
391 if(set_one_pref(val
,3,tok
,zip
,&nzip
))
394 else if (ascii_strcasecmp(tok
,"mdc")==0)
396 else if (ascii_strcasecmp(tok
,"no-mdc")==0)
398 else if (ascii_strcasecmp(tok
,"ks-modify")==0)
400 else if (ascii_strcasecmp(tok
,"no-ks-modify")==0)
404 log_info (_("invalid item `%s' in preference string\n"),tok
);
406 /* Complain if IDEA is not available. */
407 if(ascii_strcasecmp(tok
,"s1")==0
408 || ascii_strcasecmp(tok
,"idea")==0)
422 if(personal
==PREFTYPE_SYM
)
424 xfree(opt
.personal_cipher_prefs
);
427 opt
.personal_cipher_prefs
=NULL
;
432 opt
.personal_cipher_prefs
=
433 xmalloc(sizeof(prefitem_t
*)*(nsym
+1));
435 for (i
=0; i
<nsym
; i
++)
437 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_SYM
;
438 opt
.personal_cipher_prefs
[i
].value
= sym
[i
];
441 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_NONE
;
442 opt
.personal_cipher_prefs
[i
].value
= 0;
445 else if(personal
==PREFTYPE_HASH
)
447 xfree(opt
.personal_digest_prefs
);
450 opt
.personal_digest_prefs
=NULL
;
455 opt
.personal_digest_prefs
=
456 xmalloc(sizeof(prefitem_t
*)*(nhash
+1));
458 for (i
=0; i
<nhash
; i
++)
460 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_HASH
;
461 opt
.personal_digest_prefs
[i
].value
= hash
[i
];
464 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_NONE
;
465 opt
.personal_digest_prefs
[i
].value
= 0;
468 else if(personal
==PREFTYPE_ZIP
)
470 xfree(opt
.personal_compress_prefs
);
473 opt
.personal_compress_prefs
=NULL
;
478 opt
.personal_compress_prefs
=
479 xmalloc(sizeof(prefitem_t
*)*(nzip
+1));
481 for (i
=0; i
<nzip
; i
++)
483 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_ZIP
;
484 opt
.personal_compress_prefs
[i
].value
= zip
[i
];
487 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_NONE
;
488 opt
.personal_compress_prefs
[i
].value
= 0;
494 memcpy (sym_prefs
, sym
, (nsym_prefs
=nsym
));
495 memcpy (hash_prefs
, hash
, (nhash_prefs
=nhash
));
496 memcpy (zip_prefs
, zip
, (nzip_prefs
=nzip
));
499 prefs_initialized
= 1;
506 /* Return a fake user ID containing the preferences. Caller must
508 PKT_user_id
*keygen_get_std_prefs(void)
511 PKT_user_id
*uid
=xmalloc_clear(sizeof(PKT_user_id
));
513 if(!prefs_initialized
)
514 keygen_set_std_prefs(NULL
,0);
518 uid
->prefs
=xmalloc((sizeof(prefitem_t
*)*
519 (nsym_prefs
+nhash_prefs
+nzip_prefs
+1)));
521 for(i
=0;i
<nsym_prefs
;i
++,j
++)
523 uid
->prefs
[j
].type
=PREFTYPE_SYM
;
524 uid
->prefs
[j
].value
=sym_prefs
[i
];
527 for(i
=0;i
<nhash_prefs
;i
++,j
++)
529 uid
->prefs
[j
].type
=PREFTYPE_HASH
;
530 uid
->prefs
[j
].value
=hash_prefs
[i
];
533 for(i
=0;i
<nzip_prefs
;i
++,j
++)
535 uid
->prefs
[j
].type
=PREFTYPE_ZIP
;
536 uid
->prefs
[j
].value
=zip_prefs
[i
];
539 uid
->prefs
[j
].type
=PREFTYPE_NONE
;
540 uid
->prefs
[j
].value
=0;
542 uid
->flags
.mdc
=mdc_available
;
543 uid
->flags
.ks_modify
=ks_modify
;
549 add_feature_mdc (PKT_signature
*sig
,int enabled
)
556 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
, &n
);
557 /* Already set or cleared */
559 ((enabled
&& (s
[0] & 0x01)) || (!enabled
&& !(s
[0] & 0x01))))
562 if (!s
|| !n
) { /* create a new one */
564 buf
= xmalloc_clear (n
);
572 buf
[0] |= 0x01; /* MDC feature */
576 /* Are there any bits set? */
582 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
);
584 build_sig_subpkt (sig
, SIGSUBPKT_FEATURES
, buf
, n
);
590 add_keyserver_modify (PKT_signature
*sig
,int enabled
)
597 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
600 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
, &n
);
601 /* Already set or cleared */
603 ((enabled
&& (s
[0] & 0x80)) || (!enabled
&& !(s
[0] & 0x80))))
606 if (!s
|| !n
) { /* create a new one */
608 buf
= xmalloc_clear (n
);
616 buf
[0] |= 0x80; /* no-modify flag */
620 /* Are there any bits set? */
626 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
);
628 build_sig_subpkt (sig
, SIGSUBPKT_KS_FLAGS
, buf
, n
);
634 keygen_upd_std_prefs( PKT_signature
*sig
, void *opaque
)
636 if (!prefs_initialized
)
637 keygen_set_std_prefs (NULL
, 0);
640 build_sig_subpkt (sig
, SIGSUBPKT_PREF_SYM
, sym_prefs
, nsym_prefs
);
643 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_SYM
);
644 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_SYM
);
648 build_sig_subpkt (sig
, SIGSUBPKT_PREF_HASH
, hash_prefs
, nhash_prefs
);
651 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_HASH
);
652 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_HASH
);
656 build_sig_subpkt (sig
, SIGSUBPKT_PREF_COMPR
, zip_prefs
, nzip_prefs
);
659 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_COMPR
);
660 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_COMPR
);
663 /* Make sure that the MDC feature flag is set if needed */
664 add_feature_mdc (sig
,mdc_available
);
665 add_keyserver_modify (sig
,ks_modify
);
666 keygen_add_keyserver_url(sig
,NULL
);
673 * Add preference to the self signature packet.
674 * This is only called for packets with version > 3.
678 keygen_add_std_prefs( PKT_signature
*sig
, void *opaque
)
680 PKT_public_key
*pk
= opaque
;
682 do_add_key_flags (sig
, pk
->pubkey_usage
);
683 keygen_add_key_expire( sig
, opaque
);
684 keygen_upd_std_prefs (sig
, opaque
);
685 keygen_add_keyserver_url(sig
,NULL
);
691 keygen_add_keyserver_url(PKT_signature
*sig
, void *opaque
)
693 const char *url
=opaque
;
696 url
=opt
.def_keyserver_url
;
699 build_sig_subpkt(sig
,SIGSUBPKT_PREF_KS
,url
,strlen(url
));
701 delete_sig_subpkt (sig
->hashed
,SIGSUBPKT_PREF_KS
);
707 keygen_add_notations(PKT_signature
*sig
,void *opaque
)
709 struct notation
*notation
;
711 /* We always start clean */
712 delete_sig_subpkt(sig
->hashed
,SIGSUBPKT_NOTATION
);
713 delete_sig_subpkt(sig
->unhashed
,SIGSUBPKT_NOTATION
);
714 sig
->flags
.notation
=0;
716 for(notation
=opaque
;notation
;notation
=notation
->next
)
717 if(!notation
->flags
.ignore
)
722 n1
=strlen(notation
->name
);
723 if(notation
->altvalue
)
724 n2
=strlen(notation
->altvalue
);
725 else if(notation
->bdat
)
728 n2
=strlen(notation
->value
);
730 buf
= xmalloc( 8 + n1
+ n2
);
732 /* human readable or not */
733 buf
[0] = notation
->bdat
?0:0x80;
734 buf
[1] = buf
[2] = buf
[3] = 0;
739 memcpy(buf
+8, notation
->name
, n1
);
740 if(notation
->altvalue
)
741 memcpy(buf
+8+n1
, notation
->altvalue
, n2
);
742 else if(notation
->bdat
)
743 memcpy(buf
+8+n1
, notation
->bdat
, n2
);
745 memcpy(buf
+8+n1
, notation
->value
, n2
);
746 build_sig_subpkt( sig
, SIGSUBPKT_NOTATION
|
747 (notation
->flags
.critical
?SIGSUBPKT_FLAG_CRITICAL
:0),
756 keygen_add_revkey(PKT_signature
*sig
, void *opaque
)
758 struct revocation_key
*revkey
=opaque
;
759 byte buf
[2+MAX_FINGERPRINT_LEN
];
761 buf
[0]=revkey
->class;
762 buf
[1]=revkey
->algid
;
763 memcpy(&buf
[2],revkey
->fpr
,MAX_FINGERPRINT_LEN
);
765 build_sig_subpkt(sig
,SIGSUBPKT_REV_KEY
,buf
,2+MAX_FINGERPRINT_LEN
);
767 /* All sigs with revocation keys set are nonrevocable */
768 sig
->flags
.revocable
=0;
770 build_sig_subpkt( sig
, SIGSUBPKT_REVOCABLE
, buf
, 1 );
779 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
780 signature creation time. */
782 make_backsig (PKT_signature
*sig
,PKT_public_key
*pk
,
783 PKT_public_key
*sub_pk
,PKT_secret_key
*sub_sk
,
786 PKT_signature
*backsig
;
789 cache_public_key(sub_pk
);
791 rc
= make_keysig_packet (&backsig
, pk
, NULL
, sub_pk
, sub_sk
, 0x19,
792 0, 0, timestamp
, 0, NULL
, NULL
);
794 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc
));
797 /* Get it into a binary packed form. */
798 IOBUF backsig_out
=iobuf_temp();
801 init_packet(&backsig_pkt
);
802 backsig_pkt
.pkttype
=PKT_SIGNATURE
;
803 backsig_pkt
.pkt
.signature
=backsig
;
804 rc
=build_packet(backsig_out
,&backsig_pkt
);
805 free_packet(&backsig_pkt
);
807 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc
));
811 byte
*buf
=iobuf_get_temp_buffer(backsig_out
);
813 /* Remove the packet header */
823 pktlen
=(buf
[1]-192)*256;
829 pktlen
=buf
[2] << 24;
830 pktlen
|=buf
[3] << 16;
849 pktlen
=buf
[mark
++] << 24;
850 pktlen
|=buf
[mark
++] << 16;
853 pktlen
|=buf
[mark
++] << 8;
862 /* Now make the binary blob into a subpacket. */
863 build_sig_subpkt(sig
,SIGSUBPKT_SIGNATURE
,buf
,pktlen
);
865 iobuf_close(backsig_out
);
874 write_direct_sig (KBNODE root
, KBNODE pub_root
, PKT_secret_key
*sk
,
875 struct revocation_key
*revkey
, u32 timestamp
)
884 log_info(_("writing direct signature\n"));
886 /* Get the pk packet from the pub_tree. */
887 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
890 pk
= node
->pkt
->pkt
.public_key
;
892 /* We have to cache the key, so that the verification of the
893 signature creation is able to retrieve the public key. */
894 cache_public_key (pk
);
896 /* Make the signature. */
897 rc
= make_keysig_packet (&sig
,pk
,NULL
,NULL
,sk
,0x1F,
899 keygen_add_revkey
, revkey
);
902 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
906 pkt
= xmalloc_clear( sizeof *pkt
);
907 pkt
->pkttype
= PKT_SIGNATURE
;
908 pkt
->pkt
.signature
= sig
;
909 add_kbnode( root
, new_kbnode( pkt
) );
915 write_selfsigs( KBNODE sec_root
, KBNODE pub_root
, PKT_secret_key
*sk
,
916 unsigned int use
, u32 timestamp
)
926 log_info(_("writing self signature\n"));
928 /* Get the uid packet from the list. */
929 node
= find_kbnode( pub_root
, PKT_USER_ID
);
931 BUG(); /* No user id packet in tree. */
932 uid
= node
->pkt
->pkt
.user_id
;
934 /* Get the pk packet from the pub_tree. */
935 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
938 pk
= node
->pkt
->pkt
.public_key
;
939 pk
->pubkey_usage
= use
;
941 /* We have to cache the key, so that the verification of the
942 signature creation is able to retrieve the public key. */
943 cache_public_key (pk
);
945 /* Make the signature. */
946 rc
= make_keysig_packet (&sig
, pk
, uid
, NULL
, sk
, 0x13,
948 keygen_add_std_prefs
, pk
);
951 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
955 pkt
= xmalloc_clear( sizeof *pkt
);
956 pkt
->pkttype
= PKT_SIGNATURE
;
957 pkt
->pkt
.signature
= sig
;
958 add_kbnode( sec_root
, new_kbnode( pkt
) );
960 pkt
= xmalloc_clear( sizeof *pkt
);
961 pkt
->pkttype
= PKT_SIGNATURE
;
962 pkt
->pkt
.signature
= copy_signature(NULL
,sig
);
963 add_kbnode( pub_root
, new_kbnode( pkt
) );
968 /* Write the key binding signature. If TIMESTAMP is not NULL use the
969 signature creation times. */
971 write_keybinding (KBNODE root
, KBNODE pub_root
,
972 PKT_secret_key
*pri_sk
, PKT_secret_key
*sub_sk
,
973 unsigned int use
, u32 timestamp
)
979 PKT_public_key
*pri_pk
, *sub_pk
;
980 struct opaque_data_usage_and_pk oduap
;
983 log_info(_("writing key binding signature\n"));
985 /* Get the pk packet from the pub_tree. */
986 node
= find_kbnode ( pub_root
, PKT_PUBLIC_KEY
);
989 pri_pk
= node
->pkt
->pkt
.public_key
;
991 /* We have to cache the key, so that the verification of the
992 * signature creation is able to retrieve the public key. */
993 cache_public_key (pri_pk
);
995 /* Find the last subkey. */
997 for (node
=pub_root
; node
; node
= node
->next
)
999 if ( node
->pkt
->pkttype
== PKT_PUBLIC_SUBKEY
)
1000 sub_pk
= node
->pkt
->pkt
.public_key
;
1005 /* Make the signature. */
1008 rc
= make_keysig_packet (&sig
, pri_pk
, NULL
, sub_pk
, pri_sk
, 0x18,
1010 keygen_add_key_flags_and_expire
, &oduap
);
1013 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
1017 /* Make a backsig. */
1018 if (use
&PUBKEY_USAGE_SIG
)
1020 rc
= make_backsig (sig
, pri_pk
, sub_pk
, sub_sk
, timestamp
);
1025 pkt
= xmalloc_clear ( sizeof *pkt
);
1026 pkt
->pkttype
= PKT_SIGNATURE
;
1027 pkt
->pkt
.signature
= sig
;
1028 add_kbnode (root
, new_kbnode (pkt
) );
1035 key_from_sexp (gcry_mpi_t
*array
, gcry_sexp_t sexp
,
1036 const char *topname
, const char *elems
)
1038 gcry_sexp_t list
, l2
;
1043 list
= gcry_sexp_find_token (sexp
, topname
, 0);
1045 return gpg_error (GPG_ERR_INV_OBJ
);
1046 l2
= gcry_sexp_cadr (list
);
1047 gcry_sexp_release (list
);
1050 return gpg_error (GPG_ERR_NO_OBJ
);
1052 for (idx
=0,s
=elems
; *s
; s
++, idx
++)
1054 l2
= gcry_sexp_find_token (list
, s
, 1);
1057 rc
= gpg_error (GPG_ERR_NO_OBJ
); /* required parameter not found */
1060 array
[idx
] = gcry_sexp_nth_mpi (l2
, 1, GCRYMPI_FMT_USG
);
1061 gcry_sexp_release (l2
);
1064 rc
= gpg_error (GPG_ERR_INV_OBJ
); /* required parameter invalid */
1068 gcry_sexp_release (list
);
1073 for (i
=0; i
<idx
; i
++)
1078 gcry_sexp_release (list
);
1085 genhelp_protect (DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
*sk
)
1091 sk
->protect
.algo
= dek
->algo
;
1092 sk
->protect
.s2k
= *s2k
;
1093 rc
= protect_secret_key (sk
, dek
);
1095 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc
) );
1102 genhelp_factors (gcry_sexp_t misc_key_info
, KBNODE sec_root
)
1104 #if 0 /* Not used anymore */
1110 /* DSA: don't know whether it makes sense to have the factors, so for now
1111 we store them in the secret keyring (but they are not secret)
1112 p = 2 * q * f1 * f2 * ... * fn
1113 We store only f1 to f_n-1; fn can be calculated because p and q
1115 n
= gcry_sexp_sprint (misc_key_info
, 0, NULL
, 0);
1116 buf
= xmalloc (n
+4);
1117 strcpy (buf
, "#::");
1118 n
= gcry_sexp_sprint (misc_key_info
, 0, buf
+3, n
);
1122 add_kbnode (sec_root
, make_comment_node_from_buffer (buf
, n
));
1125 gcry_sexp_release (misc_key_info
);
1131 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1132 time to be put into the key structure. */
1134 gen_elg (int algo
, unsigned int nbits
,
1135 KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1136 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1137 u32 timestamp
, u32 expireval
, int is_subkey
)
1143 gcry_sexp_t s_parms
, s_key
;
1144 gcry_sexp_t misc_key_info
;
1146 assert( is_ELGAMAL(algo
) );
1151 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1156 nbits
= ((nbits
+ 31) / 32) * 32;
1157 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1161 rc
= gcry_sexp_build ( &s_parms
, NULL
,
1162 "(genkey(%s(nbits %d)))",
1163 algo
== GCRY_PK_ELG_E
? "openpgp-elg" :
1164 algo
== GCRY_PK_ELG
? "elg" : "x-oops" ,
1167 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1169 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1170 gcry_sexp_release (s_parms
);
1173 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1177 sk
= xmalloc_clear( sizeof *sk
);
1178 pk
= xmalloc_clear( sizeof *pk
);
1179 sk
->timestamp
= pk
->timestamp
= timestamp
;
1180 sk
->version
= pk
->version
= 4;
1183 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1185 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1187 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pgy");
1190 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1191 gcry_sexp_release (s_key
);
1192 free_secret_key (sk
);
1193 free_public_key (pk
);
1196 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pgyx");
1199 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1200 gcry_sexp_release (s_key
);
1201 free_secret_key (sk
);
1202 free_public_key (pk
);
1205 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1206 gcry_sexp_release (s_key
);
1208 sk
->is_protected
= 0;
1209 sk
->protect
.algo
= 0;
1211 sk
->csum
= checksum_mpi (sk
->skey
[3]);
1212 if (ret_sk
) /* Return an unprotected version of the sk. */
1213 *ret_sk
= copy_secret_key ( NULL
, sk
);
1215 rc
= genhelp_protect (dek
, s2k
, sk
);
1218 free_public_key (pk
);
1219 free_secret_key (sk
);
1220 gcry_sexp_release (misc_key_info
);
1224 pkt
= xmalloc_clear (sizeof *pkt
);
1225 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1226 pkt
->pkt
.public_key
= pk
;
1227 add_kbnode (pub_root
, new_kbnode( pkt
));
1229 /* Don't know whether it makes sense to have access to the factors,
1230 so for now we store them in the secret keyring (but they are not
1232 pkt
= xmalloc_clear (sizeof *pkt
);
1233 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1234 pkt
->pkt
.secret_key
= sk
;
1235 add_kbnode (sec_root
, new_kbnode( pkt
));
1237 genhelp_factors (misc_key_info
, sec_root
);
1244 * Generate a DSA key
1247 gen_dsa (unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1248 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1249 u32 timestamp
, u32 expireval
, int is_subkey
)
1255 gcry_sexp_t s_parms
, s_key
;
1256 gcry_sexp_t misc_key_info
;
1259 if ( nbits
< 512 || (!opt
.flags
.dsa2
&& nbits
> 1024))
1262 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1264 else if ( nbits
> 3072 )
1267 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1272 nbits
= ((nbits
+ 63) / 64) * 64;
1273 log_info(_("keysize rounded up to %u bits\n"), nbits
);
1277 Figure out a q size based on the key size. FIPS 180-3 says:
1284 2048/256 is an odd pair since there is also a 2048/224 and
1285 3072/256. Matching sizes is not a very exact science.
1287 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1288 but less than 2048, and 160 for 1024 (DSA1).
1293 else if ( nbits
> 1024)
1299 log_info (_("WARNING: some OpenPGP programs can't"
1300 " handle a DSA key with this digest size\n"));
1302 rc
= gcry_sexp_build (&s_parms
, NULL
,
1303 "(genkey(dsa(nbits %d)(qbits %d)))",
1304 (int)nbits
, (int)qbits
);
1306 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1308 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1309 gcry_sexp_release (s_parms
);
1312 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1316 sk
= xmalloc_clear( sizeof *sk
);
1317 pk
= xmalloc_clear( sizeof *pk
);
1318 sk
->timestamp
= pk
->timestamp
= timestamp
;
1319 sk
->version
= pk
->version
= 4;
1321 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1322 sk
->pubkey_algo
= pk
->pubkey_algo
= PUBKEY_ALGO_DSA
;
1324 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pqgy");
1327 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1328 gcry_sexp_release (s_key
);
1329 free_public_key(pk
);
1330 free_secret_key(sk
);
1333 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pqgyx");
1336 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1337 gcry_sexp_release (s_key
);
1338 free_public_key(pk
);
1339 free_secret_key(sk
);
1342 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1343 gcry_sexp_release (s_key
);
1345 sk
->is_protected
= 0;
1346 sk
->protect
.algo
= 0;
1348 sk
->csum
= checksum_mpi ( sk
->skey
[4] );
1349 if( ret_sk
) /* return an unprotected version of the sk */
1350 *ret_sk
= copy_secret_key( NULL
, sk
);
1352 rc
= genhelp_protect (dek
, s2k
, sk
);
1355 free_public_key (pk
);
1356 free_secret_key (sk
);
1357 gcry_sexp_release (misc_key_info
);
1361 pkt
= xmalloc_clear(sizeof *pkt
);
1362 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1363 pkt
->pkt
.public_key
= pk
;
1364 add_kbnode(pub_root
, new_kbnode( pkt
));
1366 /* Don't know whether it makes sense to have the factors, so for now
1367 * we store them in the secret keyring (but they are not secret)
1368 * p = 2 * q * f1 * f2 * ... * fn
1369 * We store only f1 to f_n-1; fn can be calculated because p and q
1372 pkt
= xmalloc_clear(sizeof *pkt
);
1373 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1374 pkt
->pkt
.secret_key
= sk
;
1375 add_kbnode(sec_root
, new_kbnode( pkt
));
1377 genhelp_factors (misc_key_info
, sec_root
);
1384 * Generate an RSA key.
1387 gen_rsa (int algo
, unsigned nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1388 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1389 u32 timestamp
, u32 expireval
, int is_subkey
)
1395 gcry_sexp_t s_parms
, s_key
;
1397 assert (is_RSA(algo
));
1402 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1407 nbits
= ((nbits
+ 31) / 32) * 32;
1408 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1411 rc
= gcry_sexp_build (&s_parms
, NULL
,
1412 "(genkey(rsa(nbits %d)))",
1415 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1417 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1418 gcry_sexp_release (s_parms
);
1421 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1425 sk
= xmalloc_clear( sizeof *sk
);
1426 pk
= xmalloc_clear( sizeof *pk
);
1427 sk
->timestamp
= pk
->timestamp
= timestamp
;
1428 sk
->version
= pk
->version
= 4;
1431 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1433 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1435 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "ne");
1438 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1439 gcry_sexp_release (s_key
);
1440 free_public_key(pk
);
1441 free_secret_key(sk
);
1444 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
1447 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1448 gcry_sexp_release (s_key
);
1449 free_public_key(pk
);
1450 free_secret_key(sk
);
1453 gcry_sexp_release (s_key
);
1455 sk
->is_protected
= 0;
1456 sk
->protect
.algo
= 0;
1458 sk
->csum
= checksum_mpi (sk
->skey
[2] );
1459 sk
->csum
+= checksum_mpi (sk
->skey
[3] );
1460 sk
->csum
+= checksum_mpi (sk
->skey
[4] );
1461 sk
->csum
+= checksum_mpi (sk
->skey
[5] );
1462 if( ret_sk
) /* return an unprotected version of the sk */
1463 *ret_sk
= copy_secret_key( NULL
, sk
);
1465 rc
= genhelp_protect (dek
, s2k
, sk
);
1468 free_public_key (pk
);
1469 free_secret_key (sk
);
1473 pkt
= xmalloc_clear(sizeof *pkt
);
1474 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1475 pkt
->pkt
.public_key
= pk
;
1476 add_kbnode(pub_root
, new_kbnode( pkt
));
1478 pkt
= xmalloc_clear(sizeof *pkt
);
1479 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1480 pkt
->pkt
.secret_key
= sk
;
1481 add_kbnode(sec_root
, new_kbnode( pkt
));
1489 * return 0 on error or the multiplier
1492 check_valid_days( const char *s
)
1502 return 0; /* e.g. "2323wc" */
1503 if( *s
== 'd' || *s
== 'D' )
1505 if( *s
== 'w' || *s
== 'W' )
1507 if( *s
== 'm' || *s
== 'M' )
1509 if( *s
== 'y' || *s
== 'Y' )
1516 print_key_flags(int flags
)
1518 if(flags
&PUBKEY_USAGE_SIG
)
1519 tty_printf("%s ",_("Sign"));
1521 if(flags
&PUBKEY_USAGE_CERT
)
1522 tty_printf("%s ",_("Certify"));
1524 if(flags
&PUBKEY_USAGE_ENC
)
1525 tty_printf("%s ",_("Encrypt"));
1527 if(flags
&PUBKEY_USAGE_AUTH
)
1528 tty_printf("%s ",_("Authenticate"));
1532 /* Returns the key flags */
1534 ask_key_flags(int algo
,int subkey
)
1536 /* TRANSLATORS: Please use only plain ASCII characters for the
1537 translation. If this is not possible use single digits. The
1538 string needs to 8 bytes long. Here is a description of the
1541 s = Toggle signing capability
1542 e = Toggle encryption capability
1543 a = Toggle authentication capability
1546 const char *togglers
=_("SsEeAaQq");
1548 unsigned int current
=0;
1549 unsigned int possible
=openpgp_pk_algo_usage(algo
);
1551 if ( strlen(togglers
) != 7 )
1553 tty_printf ("NOTE: Bad translation at %s:%d. "
1554 "Please report.\n", __FILE__
, __LINE__
);
1555 togglers
= "11223300";
1558 /* Only primary keys may certify. */
1560 possible
&=~PUBKEY_USAGE_CERT
;
1562 /* Preload the current set with the possible set, minus
1563 authentication, since nobody really uses auth yet. */
1564 current
=possible
&~PUBKEY_USAGE_AUTH
;
1569 tty_printf(_("Possible actions for a %s key: "),
1570 gcry_pk_algo_name (algo
));
1571 print_key_flags(possible
);
1573 tty_printf(_("Current allowed actions: "));
1574 print_key_flags(current
);
1577 if(possible
&PUBKEY_USAGE_SIG
)
1578 tty_printf(_(" (%c) Toggle the sign capability\n"),
1580 if(possible
&PUBKEY_USAGE_ENC
)
1581 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1583 if(possible
&PUBKEY_USAGE_AUTH
)
1584 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1587 tty_printf(_(" (%c) Finished\n"),togglers
[6]);
1591 answer
= cpr_get("keygen.flags",_("Your selection? "));
1594 if(strlen(answer
)>1)
1595 tty_printf(_("Invalid selection.\n"));
1596 else if(*answer
=='\0' || *answer
==togglers
[6] || *answer
==togglers
[7])
1598 else if((*answer
==togglers
[0] || *answer
==togglers
[1])
1599 && possible
&PUBKEY_USAGE_SIG
)
1601 if(current
&PUBKEY_USAGE_SIG
)
1602 current
&=~PUBKEY_USAGE_SIG
;
1604 current
|=PUBKEY_USAGE_SIG
;
1606 else if((*answer
==togglers
[2] || *answer
==togglers
[3])
1607 && possible
&PUBKEY_USAGE_ENC
)
1609 if(current
&PUBKEY_USAGE_ENC
)
1610 current
&=~PUBKEY_USAGE_ENC
;
1612 current
|=PUBKEY_USAGE_ENC
;
1614 else if((*answer
==togglers
[4] || *answer
==togglers
[5])
1615 && possible
&PUBKEY_USAGE_AUTH
)
1617 if(current
&PUBKEY_USAGE_AUTH
)
1618 current
&=~PUBKEY_USAGE_AUTH
;
1620 current
|=PUBKEY_USAGE_AUTH
;
1623 tty_printf(_("Invalid selection.\n"));
1633 * Returns: 0 to create both a DSA and a Elgamal key.
1634 * and only if key flags are to be written the desired usage.
1637 ask_algo (int addmode
, unsigned int *r_usage
)
1643 tty_printf(_("Please select what kind of key you want:\n"));
1645 tty_printf(_(" (%d) DSA and Elgamal (default)\n"), 1 );
1646 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
1648 tty_printf( _(" (%d) DSA (set your own capabilities)\n"), 3 );
1650 tty_printf(_(" (%d) Elgamal (encrypt only)\n"), 4 );
1651 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
1653 tty_printf(_(" (%d) RSA (encrypt only)\n"), 6 );
1655 tty_printf( _(" (%d) RSA (set your own capabilities)\n"), 7 );
1658 answer
= cpr_get("keygen.algo",_("Your selection? "));
1660 algo
= *answer
? atoi(answer
): 1;
1662 if( algo
== 1 && !addmode
) {
1663 algo
= 0; /* create both keys */
1666 else if( algo
== 7 && opt
.expert
) {
1667 algo
= PUBKEY_ALGO_RSA
;
1668 *r_usage
=ask_key_flags(algo
,addmode
);
1671 else if( algo
== 6 && addmode
) {
1672 algo
= PUBKEY_ALGO_RSA
;
1673 *r_usage
= PUBKEY_USAGE_ENC
;
1676 else if( algo
== 5 ) {
1677 algo
= PUBKEY_ALGO_RSA
;
1678 *r_usage
= PUBKEY_USAGE_SIG
;
1681 else if( algo
== 4 && addmode
) {
1682 algo
= PUBKEY_ALGO_ELGAMAL_E
;
1683 *r_usage
= PUBKEY_USAGE_ENC
;
1686 else if( algo
== 3 && opt
.expert
) {
1687 algo
= PUBKEY_ALGO_DSA
;
1688 *r_usage
=ask_key_flags(algo
,addmode
);
1691 else if( algo
== 2 ) {
1692 algo
= PUBKEY_ALGO_DSA
;
1693 *r_usage
= PUBKEY_USAGE_SIG
;
1697 tty_printf(_("Invalid selection.\n"));
1705 ask_keysize( int algo
)
1707 unsigned int nbits
, min
, def
=2048, max
=4096;
1716 case PUBKEY_ALGO_DSA
:
1724 tty_printf(_("DSA keypair will have %u bits.\n"),1024);
1729 case PUBKEY_ALGO_RSA
:
1734 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1735 gcry_pk_algo_name (algo
), min
, max
);
1739 char *prompt
,*answer
;
1741 #define PROMPTSTRING _("What keysize do you want? (%u) ")
1743 prompt
=xmalloc(strlen(PROMPTSTRING
)+20);
1744 sprintf(prompt
,PROMPTSTRING
,def
);
1748 answer
= cpr_get("keygen.size",prompt
);
1750 nbits
= *answer
? atoi(answer
): def
;
1754 if(nbits
<min
|| nbits
>max
)
1755 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1756 gcry_pk_algo_name (algo
), min
, max
);
1761 tty_printf(_("Requested keysize is %u bits\n"), nbits
);
1763 if( algo
== PUBKEY_ALGO_DSA
&& (nbits
% 64) )
1765 nbits
= ((nbits
+ 63) / 64) * 64;
1766 tty_printf(_("rounded up to %u bits\n"), nbits
);
1768 else if( (nbits
% 32) )
1770 nbits
= ((nbits
+ 31) / 32) * 32;
1771 tty_printf(_("rounded up to %u bits\n"), nbits
);
1779 * Parse an expire string and return its value in seconds.
1780 * Returns (u32)-1 on error.
1781 * This isn't perfect since scan_isodatestr returns unix time, and
1782 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1783 * Because of this, we only permit setting expirations up to 2106, but
1784 * OpenPGP could theoretically allow up to 2242. I think we'll all
1785 * just cope for the next few years until we get a 64-bit time_t or
1789 parse_expire_string( const char *string
)
1792 u32 seconds
,abs_date
=0,curtime
= make_timestamp();
1796 else if ( !strncmp (string
, "seconds=", 8) )
1797 seconds
= atoi (string
+8);
1798 else if( (abs_date
= scan_isodatestr(string
)) && abs_date
> curtime
)
1799 seconds
= abs_date
- curtime
;
1800 else if( (mult
=check_valid_days(string
)) )
1801 seconds
= atoi(string
) * 86400L * mult
;
1808 /* Parsean Creation-Date string which is either "1986-04-26" or
1809 "19860426T042640". Returns 0 on error. */
1811 parse_creation_string (const char *string
)
1817 else if ( !strncmp (string
, "seconds=", 8) )
1818 seconds
= atoi (string
+8);
1819 else if ( !(seconds
= scan_isodatestr (string
)))
1821 time_t tmp
= isotime2epoch (string
);
1822 seconds
= (tmp
== (time_t)(-1))? 0 : tmp
;
1828 /* object == 0 for a key, and 1 for a sig */
1830 ask_expire_interval(int object
,const char *def_expire
)
1840 tty_printf(_("Please specify how long the key should be valid.\n"
1841 " 0 = key does not expire\n"
1842 " <n> = key expires in n days\n"
1843 " <n>w = key expires in n weeks\n"
1844 " <n>m = key expires in n months\n"
1845 " <n>y = key expires in n years\n"));
1851 tty_printf(_("Please specify how long the signature should be valid.\n"
1852 " 0 = signature does not expire\n"
1853 " <n> = signature expires in n days\n"
1854 " <n>w = signature expires in n weeks\n"
1855 " <n>m = signature expires in n months\n"
1856 " <n>y = signature expires in n years\n"));
1863 /* Note: The elgamal subkey for DSA has no expiration date because
1864 * it must be signed with the DSA key and this one has the expiration
1870 u32 curtime
=make_timestamp();
1874 answer
= cpr_get("keygen.valid",_("Key is valid for? (0) "));
1879 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1880 /* This will actually end up larger than necessary because
1881 of the 2 bytes for '%s' */
1882 prompt
=xmalloc(strlen(PROMPTSTRING
)+strlen(def_expire
)+1);
1883 sprintf(prompt
,PROMPTSTRING
,def_expire
);
1886 answer
= cpr_get("siggen.valid",prompt
);
1890 answer
=xstrdup(def_expire
);
1893 trim_spaces(answer
);
1894 interval
= parse_expire_string( answer
);
1895 if( interval
== (u32
)-1 )
1897 tty_printf(_("invalid value\n"));
1903 tty_printf((object
==0)
1904 ? _("Key does not expire at all\n")
1905 : _("Signature does not expire at all\n"));
1909 tty_printf(object
==0
1910 ? _("Key expires at %s\n")
1911 : _("Signature expires at %s\n"),
1912 asctimestamp((ulong
)(curtime
+ interval
) ) );
1913 #if SIZEOF_TIME_T <= 4
1914 if ( (time_t)((ulong
)(curtime
+interval
)) < 0 )
1915 tty_printf (_("Your system can't display dates beyond 2038.\n"
1916 "However, it will be correctly handled up to"
1918 #endif /*SIZEOF_TIME_T*/
1921 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1922 _("Is this correct? (y/N) ")) )
1933 u32 x
= ask_expire_interval(0,NULL
);
1934 return x
? make_timestamp() + x
: 0;
1939 ask_user_id( int mode
)
1942 char *aname
, *acomment
, *amail
, *uid
;
1946 "You need a user ID to identify your key; "
1947 "the software constructs the user ID\n"
1948 "from the Real Name, Comment and Email Address in this form:\n"
1949 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n") );
1950 uid
= aname
= acomment
= amail
= NULL
;
1958 aname
= cpr_get("keygen.name",_("Real name: "));
1962 if( opt
.allow_freeform_uid
)
1965 if( strpbrk( aname
, "<>" ) )
1966 tty_printf(_("Invalid character in name\n"));
1967 else if( digitp(aname
) )
1968 tty_printf(_("Name may not start with a digit\n"));
1969 else if( strlen(aname
) < 5 )
1970 tty_printf(_("Name must be at least 5 characters long\n"));
1978 amail
= cpr_get("keygen.email",_("Email address: "));
1981 if( !*amail
|| opt
.allow_freeform_uid
)
1982 break; /* no email address is okay */
1983 else if ( !is_valid_mailbox (amail
) )
1984 tty_printf(_("Not a valid email address\n"));
1992 acomment
= cpr_get("keygen.comment",_("Comment: "));
1993 trim_spaces(acomment
);
1996 break; /* no comment is okay */
1997 else if( strpbrk( acomment
, "()" ) )
1998 tty_printf(_("Invalid character in comment\n"));
2006 uid
= p
= xmalloc(strlen(aname
)+strlen(amail
)+strlen(acomment
)+12+10);
2007 p
= stpcpy(p
, aname
);
2009 p
= stpcpy(stpcpy(stpcpy(p
," ("), acomment
),")");
2011 p
= stpcpy(stpcpy(stpcpy(p
," <"), amail
),">");
2013 /* Append a warning if the RNG is switched into fake mode. */
2014 if ( random_is_faked () )
2015 strcpy(p
, " (insecure!)" );
2017 /* print a note in case that UTF8 mapping has to be done */
2018 for(p
=uid
; *p
; p
++ ) {
2020 tty_printf(_("You are using the `%s' character set.\n"),
2021 get_native_charset() );
2026 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid
);
2027 /* fixme: add a warning if this user-id already exists */
2028 if( !*amail
&& !opt
.allow_freeform_uid
2029 && (strchr( aname
, '@' ) || strchr( acomment
, '@'))) {
2031 tty_printf(_("Please don't put the email address "
2032 "into the real name or the comment\n") );
2036 /* TRANSLATORS: These are the allowed answers in
2037 lower and uppercase. Below you will find the matching
2038 string which should be translated accordingly and the
2039 letter changed to match the one in the answer string.
2044 o = Okay (ready, continue)
2047 const char *ansstr
= _("NnCcEeOoQq");
2049 if( strlen(ansstr
) != 10 )
2051 if( cpr_enabled() ) {
2052 answer
= xstrdup(ansstr
+6);
2056 answer
= cpr_get("keygen.userid.cmd", fail
?
2057 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2058 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2061 if( strlen(answer
) > 1 )
2063 else if( *answer
== ansstr
[0] || *answer
== ansstr
[1] ) {
2064 xfree(aname
); aname
= NULL
;
2067 else if( *answer
== ansstr
[2] || *answer
== ansstr
[3] ) {
2068 xfree(acomment
); acomment
= NULL
;
2071 else if( *answer
== ansstr
[4] || *answer
== ansstr
[5] ) {
2072 xfree(amail
); amail
= NULL
;
2075 else if( *answer
== ansstr
[6] || *answer
== ansstr
[7] ) {
2077 tty_printf(_("Please correct the error first\n"));
2080 xfree(aname
); aname
= NULL
;
2081 xfree(acomment
); acomment
= NULL
;
2082 xfree(amail
); amail
= NULL
;
2086 else if( *answer
== ansstr
[8] || *answer
== ansstr
[9] ) {
2087 xfree(aname
); aname
= NULL
;
2088 xfree(acomment
); acomment
= NULL
;
2089 xfree(amail
); amail
= NULL
;
2090 xfree(uid
); uid
= NULL
;
2096 if( !amail
&& !acomment
&& !amail
)
2098 xfree(uid
); uid
= NULL
;
2101 char *p
= native_to_utf8( uid
);
2110 do_ask_passphrase ( STRING2KEY
**ret_s2k
, int *r_canceled
)
2114 const char *errtext
= NULL
;
2116 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2118 s2k
= xmalloc_secure( sizeof *s2k
);
2120 s2k
->mode
= opt
.s2k_mode
;
2121 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2122 dek
= passphrase_to_dek( NULL
, 0, opt
.s2k_cipher_algo
, s2k
,2,
2123 errtext
, r_canceled
);
2124 if (!dek
&& *r_canceled
) {
2125 xfree(dek
); dek
= NULL
;
2126 xfree(s2k
); s2k
= NULL
;
2130 errtext
= N_("passphrase not correctly repeated; try again");
2131 tty_printf(_("%s.\n"), _(errtext
));
2133 else if( !dek
->keylen
) {
2134 xfree(dek
); dek
= NULL
;
2135 xfree(s2k
); s2k
= NULL
;
2137 "You don't want a passphrase - this is probably a *bad* idea!\n"
2138 "I will do it anyway. You can change your passphrase at any time,\n"
2139 "using this program with the option \"--edit-key\".\n\n"));
2150 /* Basic key generation. Here we divert to the actual generation
2151 routines based on the requested algorithm. */
2153 do_create (int algo
, unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
,
2154 DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
**sk
,
2155 u32 timestamp
, u32 expiredate
, int is_subkey
)
2161 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2162 "some other action (type on the keyboard, move the mouse, utilize the\n"
2163 "disks) during the prime generation; this gives the random number\n"
2164 "generator a better chance to gain enough entropy.\n") );
2166 if( algo
== PUBKEY_ALGO_ELGAMAL_E
)
2167 rc
= gen_elg(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2168 timestamp
, expiredate
, is_subkey
);
2169 else if( algo
== PUBKEY_ALGO_DSA
)
2170 rc
= gen_dsa(nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2171 timestamp
, expiredate
, is_subkey
);
2172 else if( algo
== PUBKEY_ALGO_RSA
)
2173 rc
= gen_rsa(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2174 timestamp
, expiredate
, is_subkey
);
2183 * Generate a new user id packet, or return NULL if canceled
2192 p
= ask_user_id( 1 );
2196 uid
= xmalloc_clear( sizeof *uid
+ n
);
2198 strcpy(uid
->name
, p
);
2205 release_parameter_list( struct para_data_s
*r
)
2207 struct para_data_s
*r2
;
2209 for( ; r
; r
= r2
) {
2211 if( r
->key
== pPASSPHRASE_DEK
)
2213 else if( r
->key
== pPASSPHRASE_S2K
)
2220 static struct para_data_s
*
2221 get_parameter( struct para_data_s
*para
, enum para_name key
)
2223 struct para_data_s
*r
;
2225 for( r
= para
; r
&& r
->key
!= key
; r
= r
->next
)
2231 get_parameter_value( struct para_data_s
*para
, enum para_name key
)
2233 struct para_data_s
*r
= get_parameter( para
, key
);
2234 return (r
&& *r
->u
.value
)? r
->u
.value
: NULL
;
2238 get_parameter_algo( struct para_data_s
*para
, enum para_name key
)
2241 struct para_data_s
*r
= get_parameter( para
, key
);
2244 if( digitp( r
->u
.value
) )
2245 i
= atoi( r
->u
.value
);
2246 else if ( !strcmp ( r
->u
.value
, "ELG-E")
2247 || !strcmp ( r
->u
.value
, "ELG") )
2250 i
= gcry_pk_map_name (r
->u
.value
);
2251 if (i
== PUBKEY_ALGO_RSA_E
|| i
== PUBKEY_ALGO_RSA_S
)
2252 i
= 0; /* we don't want to allow generation of these algorithms */
2257 * parse the usage parameter and set the keyflags. Return true on error.
2260 parse_parameter_usage (const char *fname
,
2261 struct para_data_s
*para
, enum para_name key
)
2263 struct para_data_s
*r
= get_parameter( para
, key
);
2268 return 0; /* none (this is an optional parameter)*/
2272 while ( (p
= strsep (&pn
, " \t,")) ) {
2275 else if ( !ascii_strcasecmp (p
, "sign") )
2276 use
|= PUBKEY_USAGE_SIG
;
2277 else if ( !ascii_strcasecmp (p
, "encrypt") )
2278 use
|= PUBKEY_USAGE_ENC
;
2279 else if ( !ascii_strcasecmp (p
, "auth") )
2280 use
|= PUBKEY_USAGE_AUTH
;
2282 log_error("%s:%d: invalid usage list\n", fname
, r
->lnr
);
2283 return -1; /* error */
2291 parse_revocation_key (const char *fname
,
2292 struct para_data_s
*para
, enum para_name key
)
2294 struct para_data_s
*r
= get_parameter( para
, key
);
2295 struct revocation_key revkey
;
2300 return 0; /* none (this is an optional parameter) */
2305 revkey
.algid
=atoi(pn
);
2309 /* Skip to the fpr */
2310 while(*pn
&& *pn
!=':')
2318 for(i
=0;i
<MAX_FINGERPRINT_LEN
&& *pn
;i
++,pn
+=2)
2320 int c
=hextobyte(pn
);
2327 /* skip to the tag */
2328 while(*pn
&& *pn
!='s' && *pn
!='S')
2331 if(ascii_strcasecmp(pn
,"sensitive")==0)
2334 memcpy(&r
->u
.revkey
,&revkey
,sizeof(struct revocation_key
));
2339 log_error("%s:%d: invalid revocation key\n", fname
, r
->lnr
);
2340 return -1; /* error */
2345 get_parameter_u32( struct para_data_s
*para
, enum para_name key
)
2347 struct para_data_s
*r
= get_parameter( para
, key
);
2351 if( r
->key
== pKEYCREATIONDATE
)
2352 return r
->u
.creation
;
2353 if( r
->key
== pKEYEXPIRE
|| r
->key
== pSUBKEYEXPIRE
)
2355 if( r
->key
== pKEYUSAGE
|| r
->key
== pSUBKEYUSAGE
)
2358 return (unsigned int)strtoul( r
->u
.value
, NULL
, 10 );
2362 get_parameter_uint( struct para_data_s
*para
, enum para_name key
)
2364 return get_parameter_u32( para
, key
);
2368 get_parameter_dek( struct para_data_s
*para
, enum para_name key
)
2370 struct para_data_s
*r
= get_parameter( para
, key
);
2371 return r
? r
->u
.dek
: NULL
;
2375 get_parameter_s2k( struct para_data_s
*para
, enum para_name key
)
2377 struct para_data_s
*r
= get_parameter( para
, key
);
2378 return r
? r
->u
.s2k
: NULL
;
2381 static struct revocation_key
*
2382 get_parameter_revkey( struct para_data_s
*para
, enum para_name key
)
2384 struct para_data_s
*r
= get_parameter( para
, key
);
2385 return r
? &r
->u
.revkey
: NULL
;
2389 proc_parameter_file( struct para_data_s
*para
, const char *fname
,
2390 struct output_control_s
*outctrl
, int card
)
2392 struct para_data_s
*r
;
2393 const char *s1
, *s2
, *s3
;
2396 int have_user_id
=0,err
,algo
;
2398 /* Check that we have all required parameters. */
2399 r
= get_parameter( para
, pKEYTYPE
);
2402 algo
=get_parameter_algo(para
,pKEYTYPE
);
2403 if (openpgp_pk_test_algo2 (algo
, PUBKEY_USAGE_SIG
))
2405 log_error("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2411 log_error("%s: no Key-Type specified\n",fname
);
2415 err
=parse_parameter_usage (fname
, para
, pKEYUSAGE
);
2418 /* Default to algo capabilities if key-usage is not provided */
2419 r
=xmalloc_clear(sizeof(*r
));
2421 r
->u
.usage
=openpgp_pk_algo_usage(algo
);
2428 r
= get_parameter( para
, pSUBKEYTYPE
);
2431 algo
=get_parameter_algo( para
, pSUBKEYTYPE
);
2432 if (openpgp_pk_test_algo (algo
))
2434 log_error("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2438 err
=parse_parameter_usage (fname
, para
, pSUBKEYUSAGE
);
2441 /* Default to algo capabilities if subkey-usage is not
2443 r
=xmalloc_clear(sizeof(*r
));
2444 r
->key
=pSUBKEYUSAGE
;
2445 r
->u
.usage
=openpgp_pk_algo_usage(algo
);
2453 if( get_parameter_value( para
, pUSERID
) )
2457 /* create the formatted user ID */
2458 s1
= get_parameter_value( para
, pNAMEREAL
);
2459 s2
= get_parameter_value( para
, pNAMECOMMENT
);
2460 s3
= get_parameter_value( para
, pNAMEEMAIL
);
2461 if( s1
|| s2
|| s3
)
2463 n
= (s1
?strlen(s1
):0) + (s2
?strlen(s2
):0) + (s3
?strlen(s3
):0);
2464 r
= xmalloc_clear( sizeof *r
+ n
+ 20 );
2470 p
= stpcpy(stpcpy(stpcpy(p
," ("), s2
),")");
2472 p
= stpcpy(stpcpy(stpcpy(p
," <"), s3
),">");
2481 log_error("%s: no User-ID specified\n",fname
);
2485 /* Set preferences, if any. */
2486 keygen_set_std_prefs(get_parameter_value( para
, pPREFERENCES
), 0);
2488 /* Set keyserver, if any. */
2489 s1
=get_parameter_value( para
, pKEYSERVER
);
2492 struct keyserver_spec
*spec
;
2494 spec
=parse_keyserver_uri(s1
,1,NULL
,0);
2497 free_keyserver_spec(spec
);
2498 opt
.def_keyserver_url
=s1
;
2502 log_error("%s:%d: invalid keyserver url\n", fname
, r
->lnr
);
2507 /* Set revoker, if any. */
2508 if (parse_revocation_key (fname
, para
, pREVOKER
))
2511 /* make DEK and S2K from the Passphrase */
2512 r
= get_parameter( para
, pPASSPHRASE
);
2513 if( r
&& *r
->u
.value
) {
2514 /* We have a plain text passphrase - create a DEK from it.
2515 * It is a little bit ridiculous to keep it ih secure memory
2516 * but because we do this always, why not here */
2520 s2k
= xmalloc_secure( sizeof *s2k
);
2521 s2k
->mode
= opt
.s2k_mode
;
2522 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2523 set_next_passphrase( r
->u
.value
);
2524 dek
= passphrase_to_dek( NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2526 set_next_passphrase( NULL
);
2528 memset( r
->u
.value
, 0, strlen(r
->u
.value
) );
2530 r
= xmalloc_clear( sizeof *r
);
2531 r
->key
= pPASSPHRASE_S2K
;
2535 r
= xmalloc_clear( sizeof *r
);
2536 r
->key
= pPASSPHRASE_DEK
;
2542 /* Make KEYCREATIONDATE from Creation-Date. */
2543 r
= get_parameter (para
, pCREATIONDATE
);
2544 if (r
&& *r
->u
.value
)
2548 seconds
= parse_creation_string (r
->u
.value
);
2551 log_error ("%s:%d: invalid creation date\n", fname
, r
->lnr
);
2554 r
->u
.creation
= seconds
;
2555 r
->key
= pKEYCREATIONDATE
; /* Change that entry. */
2558 /* Make KEYEXPIRE from Expire-Date. */
2559 r
= get_parameter( para
, pEXPIREDATE
);
2560 if( r
&& *r
->u
.value
)
2564 seconds
= parse_expire_string( r
->u
.value
);
2565 if( seconds
== (u32
)-1 )
2567 log_error("%s:%d: invalid expire date\n", fname
, r
->lnr
);
2570 r
->u
.expire
= seconds
;
2571 r
->key
= pKEYEXPIRE
; /* change hat entry */
2572 /* also set it for the subkey */
2573 r
= xmalloc_clear( sizeof *r
+ 20 );
2574 r
->key
= pSUBKEYEXPIRE
;
2575 r
->u
.expire
= seconds
;
2580 if( !!outctrl
->pub
.newfname
^ !!outctrl
->sec
.newfname
) {
2581 log_error("%s:%d: only one ring name is set\n", fname
, outctrl
->lnr
);
2585 do_generate_keypair( para
, outctrl
, card
);
2591 * Kludge to allow non interactive key generation controlled
2592 * by a parameter file.
2593 * Note, that string parameters are expected to be in UTF-8
2596 read_parameter_file( const char *fname
)
2598 static struct { const char *name
;
2601 { "Key-Type", pKEYTYPE
},
2602 { "Key-Length", pKEYLENGTH
},
2603 { "Key-Usage", pKEYUSAGE
},
2604 { "Subkey-Type", pSUBKEYTYPE
},
2605 { "Subkey-Length", pSUBKEYLENGTH
},
2606 { "Subkey-Usage", pSUBKEYUSAGE
},
2607 { "Name-Real", pNAMEREAL
},
2608 { "Name-Email", pNAMEEMAIL
},
2609 { "Name-Comment", pNAMECOMMENT
},
2610 { "Expire-Date", pEXPIREDATE
},
2611 { "Creation-Date", pCREATIONDATE
},
2612 { "Passphrase", pPASSPHRASE
},
2613 { "Preferences", pPREFERENCES
},
2614 { "Revoker", pREVOKER
},
2615 { "Handle", pHANDLE
},
2616 { "Keyserver", pKEYSERVER
},
2621 unsigned int maxlen
, nline
;
2624 const char *err
= NULL
;
2625 struct para_data_s
*para
, *r
;
2627 struct output_control_s outctrl
;
2629 memset( &outctrl
, 0, sizeof( outctrl
) );
2630 outctrl
.pub
.afx
= new_armor_context ();
2631 outctrl
.sec
.afx
= new_armor_context ();
2633 if( !fname
|| !*fname
)
2636 fp
= iobuf_open (fname
);
2637 if (fp
&& is_secured_file (iobuf_get_fd (fp
)))
2644 log_error (_("can't open `%s': %s\n"), fname
, strerror(errno
) );
2647 iobuf_ioctl (fp
, 3, 1, NULL
); /* No file caching. */
2654 while ( iobuf_read_line (fp
, &line
, &nline
, &maxlen
) ) {
2655 char *keyword
, *value
;
2659 err
= "line too long";
2662 for( p
= line
; isspace(*(byte
*)p
); p
++ )
2664 if( !*p
|| *p
== '#' )
2667 if( *keyword
== '%' ) {
2668 for( ; !isspace(*(byte
*)p
); p
++ )
2672 for( ; isspace(*(byte
*)p
); p
++ )
2675 trim_trailing_ws( value
, strlen(value
) );
2676 if( !ascii_strcasecmp( keyword
, "%echo" ) )
2677 log_info("%s\n", value
);
2678 else if( !ascii_strcasecmp( keyword
, "%dry-run" ) )
2680 else if( !ascii_strcasecmp( keyword
, "%commit" ) ) {
2682 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2683 print_status_key_not_created
2684 (get_parameter_value (para
, pHANDLE
));
2685 release_parameter_list( para
);
2688 else if( !ascii_strcasecmp( keyword
, "%pubring" ) ) {
2689 if( outctrl
.pub
.fname
&& !strcmp( outctrl
.pub
.fname
, value
) )
2690 ; /* still the same file - ignore it */
2692 xfree( outctrl
.pub
.newfname
);
2693 outctrl
.pub
.newfname
= xstrdup( value
);
2694 outctrl
.use_files
= 1;
2697 else if( !ascii_strcasecmp( keyword
, "%secring" ) ) {
2698 if( outctrl
.sec
.fname
&& !strcmp( outctrl
.sec
.fname
, value
) )
2699 ; /* still the same file - ignore it */
2701 xfree( outctrl
.sec
.newfname
);
2702 outctrl
.sec
.newfname
= xstrdup( value
);
2703 outctrl
.use_files
= 1;
2707 log_info("skipping control `%s' (%s)\n", keyword
, value
);
2714 if( !(p
= strchr( p
, ':' )) || p
== keyword
) {
2715 err
= "missing colon";
2720 for( ; isspace(*(byte
*)p
); p
++ )
2723 err
= "missing argument";
2727 trim_trailing_ws( value
, strlen(value
) );
2729 for(i
=0; keywords
[i
].name
; i
++ ) {
2730 if( !ascii_strcasecmp( keywords
[i
].name
, keyword
) )
2733 if( !keywords
[i
].name
) {
2734 err
= "unknown keyword";
2737 if( keywords
[i
].key
!= pKEYTYPE
&& !para
) {
2738 err
= "parameter block does not start with \"Key-Type\"";
2742 if( keywords
[i
].key
== pKEYTYPE
&& para
) {
2744 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2745 print_status_key_not_created
2746 (get_parameter_value (para
, pHANDLE
));
2747 release_parameter_list( para
);
2751 for( r
= para
; r
; r
= r
->next
) {
2752 if( r
->key
== keywords
[i
].key
)
2756 err
= "duplicate keyword";
2760 r
= xmalloc_clear( sizeof *r
+ strlen( value
) );
2762 r
->key
= keywords
[i
].key
;
2763 strcpy( r
->u
.value
, value
);
2768 log_error("%s:%d: %s\n", fname
, lnr
, err
);
2769 else if( iobuf_error (fp
) ) {
2770 log_error("%s:%d: read error\n", fname
, lnr
);
2774 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2775 print_status_key_not_created (get_parameter_value (para
, pHANDLE
));
2778 if( outctrl
.use_files
) { /* close open streams */
2779 iobuf_close( outctrl
.pub
.stream
);
2780 iobuf_close( outctrl
.sec
.stream
);
2782 /* Must invalidate that ugly cache to actually close it. */
2783 if (outctrl
.pub
.fname
)
2784 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.pub
.fname
);
2785 if (outctrl
.sec
.fname
)
2786 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.sec
.fname
);
2788 xfree( outctrl
.pub
.fname
);
2789 xfree( outctrl
.pub
.newfname
);
2790 xfree( outctrl
.sec
.fname
);
2791 xfree( outctrl
.sec
.newfname
);
2794 release_parameter_list( para
);
2796 release_armor_context (outctrl
.pub
.afx
);
2797 release_armor_context (outctrl
.sec
.afx
);
2802 * Generate a keypair (fname is only used in batch mode) If
2803 * CARD_SERIALNO is not NULL the function will create the keys on an
2804 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2805 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2806 * generate in software, imported to the card and a backup file
2807 * written to directory given by this argument .
2810 generate_keypair (const char *fname
, const char *card_serialno
,
2811 const char *backup_encryption_dir
)
2821 struct para_data_s
*para
= NULL
;
2822 struct para_data_s
*r
;
2823 struct output_control_s outctrl
;
2826 memset( &outctrl
, 0, sizeof( outctrl
) );
2828 if (opt
.batch
&& card_serialno
)
2830 /* We don't yet support unattended key generation. */
2831 log_error (_("can't do this in batch mode\n"));
2837 read_parameter_file( fname
);
2843 #ifdef ENABLE_CARD_SUPPORT
2844 r
= xcalloc (1, sizeof *r
+ strlen (card_serialno
) );
2846 strcpy( r
->u
.value
, card_serialno
);
2850 algo
= PUBKEY_ALGO_RSA
;
2852 r
= xcalloc (1, sizeof *r
+ 20 );
2854 sprintf( r
->u
.value
, "%d", algo
);
2857 r
= xcalloc (1, sizeof *r
+ 20 );
2859 strcpy (r
->u
.value
, "sign");
2863 r
= xcalloc (1, sizeof *r
+ 20 );
2864 r
->key
= pSUBKEYTYPE
;
2865 sprintf( r
->u
.value
, "%d", algo
);
2868 r
= xcalloc (1, sizeof *r
+ 20 );
2869 r
->key
= pSUBKEYUSAGE
;
2870 strcpy (r
->u
.value
, "encrypt");
2874 r
= xcalloc (1, sizeof *r
+ 20 );
2875 r
->key
= pAUTHKEYTYPE
;
2876 sprintf( r
->u
.value
, "%d", algo
);
2880 if (backup_encryption_dir
)
2882 r
= xcalloc (1, sizeof *r
+ strlen (backup_encryption_dir
) );
2883 r
->key
= pBACKUPENCDIR
;
2884 strcpy (r
->u
.value
, backup_encryption_dir
);
2888 #endif /*ENABLE_CARD_SUPPORT*/
2892 algo
= ask_algo( 0, &use
);
2894 { /* default: DSA with ElG subkey of the specified size */
2896 r
= xmalloc_clear( sizeof *r
+ 20 );
2898 sprintf( r
->u
.value
, "%d", PUBKEY_ALGO_DSA
);
2901 nbits
= ask_keysize( PUBKEY_ALGO_DSA
);
2902 r
= xmalloc_clear( sizeof *r
+ 20 );
2903 r
->key
= pKEYLENGTH
;
2904 sprintf( r
->u
.value
, "%u", nbits
);
2907 r
= xmalloc_clear( sizeof *r
+ 20 );
2909 strcpy( r
->u
.value
, "sign" );
2913 algo
= PUBKEY_ALGO_ELGAMAL_E
;
2914 r
= xmalloc_clear( sizeof *r
+ 20 );
2915 r
->key
= pSUBKEYTYPE
;
2916 sprintf( r
->u
.value
, "%d", algo
);
2919 r
= xmalloc_clear( sizeof *r
+ 20 );
2920 r
->key
= pSUBKEYUSAGE
;
2921 strcpy( r
->u
.value
, "encrypt" );
2927 r
= xmalloc_clear( sizeof *r
+ 20 );
2929 sprintf( r
->u
.value
, "%d", algo
);
2935 r
= xmalloc_clear( sizeof *r
+ 25 );
2937 sprintf( r
->u
.value
, "%s%s%s",
2938 (use
& PUBKEY_USAGE_SIG
)? "sign ":"",
2939 (use
& PUBKEY_USAGE_ENC
)? "encrypt ":"",
2940 (use
& PUBKEY_USAGE_AUTH
)? "auth":"" );
2947 nbits
= ask_keysize( algo
);
2948 r
= xmalloc_clear( sizeof *r
+ 20 );
2949 r
->key
= both
? pSUBKEYLENGTH
: pKEYLENGTH
;
2950 sprintf( r
->u
.value
, "%u", nbits
);
2955 expire
= ask_expire_interval(0,NULL
);
2956 r
= xmalloc_clear( sizeof *r
+ 20 );
2957 r
->key
= pKEYEXPIRE
;
2958 r
->u
.expire
= expire
;
2961 r
= xmalloc_clear( sizeof *r
+ 20 );
2962 r
->key
= pSUBKEYEXPIRE
;
2963 r
->u
.expire
= expire
;
2967 uid
= ask_user_id(0);
2970 log_error(_("Key generation canceled.\n"));
2971 release_parameter_list( para
);
2974 r
= xmalloc_clear( sizeof *r
+ strlen(uid
) );
2976 strcpy( r
->u
.value
, uid
);
2981 dek
= card_serialno
? NULL
: do_ask_passphrase ( &s2k
, &canceled
);
2984 r
= xmalloc_clear( sizeof *r
);
2985 r
->key
= pPASSPHRASE_DEK
;
2989 r
= xmalloc_clear( sizeof *r
);
2990 r
->key
= pPASSPHRASE_S2K
;
2997 log_error (_("Key generation canceled.\n"));
2999 proc_parameter_file( para
, "[internal]", &outctrl
, !!card_serialno
);
3000 release_parameter_list( para
);
3004 #ifdef ENABLE_CARD_SUPPORT
3005 /* Generate a raw key and return it as a secret key packet. The
3006 function will ask for the passphrase and return a protected as well
3007 as an unprotected copy of a new secret key packet. 0 is returned
3008 on success and the caller must then free the returned values. */
3010 generate_raw_key (int algo
, unsigned int nbits
, u32 created_at
,
3011 PKT_secret_key
**r_sk_unprotected
,
3012 PKT_secret_key
**r_sk_protected
)
3016 STRING2KEY
*s2k
= NULL
;
3017 PKT_secret_key
*sk
= NULL
;
3019 size_t nskey
, npkey
;
3020 gcry_sexp_t s_parms
, s_key
;
3023 npkey
= pubkey_get_npkey (algo
);
3024 nskey
= pubkey_get_nskey (algo
);
3025 assert (nskey
<= PUBKEY_MAX_NSKEY
&& npkey
< nskey
);
3030 log_info (_("keysize invalid; using %u bits\n"), nbits
);
3035 nbits
= ((nbits
+ 31) / 32) * 32;
3036 log_info(_("keysize rounded up to %u bits\n"), nbits
);
3039 dek
= do_ask_passphrase (&s2k
, &canceled
);
3042 rc
= gpg_error (GPG_ERR_CANCELED
);
3046 sk
= xmalloc_clear (sizeof *sk
);
3047 sk
->timestamp
= created_at
;
3049 sk
->pubkey_algo
= algo
;
3051 if ( !is_RSA (algo
) )
3053 log_error ("only RSA is supported for offline generated keys\n");
3054 rc
= gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
3057 rc
= gcry_sexp_build (&s_parms
, NULL
,
3058 "(genkey(rsa(nbits %d)))",
3061 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
3062 rc
= gcry_pk_genkey (&s_key
, s_parms
);
3063 gcry_sexp_release (s_parms
);
3066 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
3069 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
3070 gcry_sexp_release (s_key
);
3073 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
3077 for (i
=npkey
; i
< nskey
; i
++)
3078 sk
->csum
+= checksum_mpi (sk
->skey
[i
]);
3080 if (r_sk_unprotected
)
3081 *r_sk_unprotected
= copy_secret_key (NULL
, sk
);
3083 rc
= genhelp_protect (dek
, s2k
, sk
);
3089 *r_sk_protected
= sk
;
3095 free_secret_key (sk
);
3100 #endif /* ENABLE_CARD_SUPPORT */
3102 /* Create and delete a dummy packet to start off a list of kbnodes. */
3104 start_tree(KBNODE
*tree
)
3108 pkt
=xmalloc_clear(sizeof(*pkt
));
3109 pkt
->pkttype
=PKT_NONE
;
3110 *tree
=new_kbnode(pkt
);
3111 delete_kbnode(*tree
);
3116 do_generate_keypair (struct para_data_s
*para
,
3117 struct output_control_s
*outctrl
, int card
)
3119 KBNODE pub_root
= NULL
;
3120 KBNODE sec_root
= NULL
;
3121 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3123 struct revocation_key
*revkey
;
3128 if( outctrl
->dryrun
)
3130 log_info("dry-run mode - key generation skipped\n");
3134 if ( outctrl
->use_files
)
3136 if ( outctrl
->pub
.newfname
)
3138 iobuf_close(outctrl
->pub
.stream
);
3139 outctrl
->pub
.stream
= NULL
;
3140 if (outctrl
->pub
.fname
)
3141 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->pub
.fname
);
3142 xfree( outctrl
->pub
.fname
);
3143 outctrl
->pub
.fname
= outctrl
->pub
.newfname
;
3144 outctrl
->pub
.newfname
= NULL
;
3146 if (is_secured_filename (outctrl
->pub
.fname
) )
3148 outctrl
->pub
.stream
= NULL
;
3152 outctrl
->pub
.stream
= iobuf_create( outctrl
->pub
.fname
);
3153 if (!outctrl
->pub
.stream
)
3155 log_error(_("can't create `%s': %s\n"), outctrl
->pub
.newfname
,
3161 outctrl
->pub
.afx
->what
= 1;
3162 push_armor_filter (outctrl
->pub
.afx
, outctrl
->pub
.stream
);
3165 if (outctrl
->sec
.newfname
)
3169 iobuf_close(outctrl
->sec
.stream
);
3170 outctrl
->sec
.stream
= NULL
;
3171 if (outctrl
->sec
.fname
)
3172 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->sec
.fname
);
3173 xfree( outctrl
->sec
.fname
);
3174 outctrl
->sec
.fname
= outctrl
->sec
.newfname
;
3175 outctrl
->sec
.newfname
= NULL
;
3177 oldmask
= umask (077);
3178 if (is_secured_filename (outctrl
->sec
.fname
) )
3180 outctrl
->sec
.stream
= NULL
;
3184 outctrl
->sec
.stream
= iobuf_create( outctrl
->sec
.fname
);
3186 if (!outctrl
->sec
.stream
)
3188 log_error(_("can't create `%s': %s\n"), outctrl
->sec
.newfname
,
3194 outctrl
->sec
.afx
->what
= 5;
3195 push_armor_filter (outctrl
->sec
.afx
, outctrl
->sec
.stream
);
3198 assert( outctrl
->pub
.stream
);
3199 assert( outctrl
->sec
.stream
);
3202 log_info (_("writing public key to `%s'\n"), outctrl
->pub
.fname
);
3204 log_info (_("writing secret key stub to `%s'\n"),
3205 outctrl
->sec
.fname
);
3207 log_info(_("writing secret key to `%s'\n"), outctrl
->sec
.fname
);
3212 /* We create the packets as a tree of kbnodes. Because the
3213 structure we create is known in advance we simply generate a
3214 linked list. The first packet is a dummy packet which we flag as
3215 deleted. The very first packet must always be a KEY packet. */
3217 start_tree (&pub_root
);
3218 start_tree (&sec_root
);
3220 timestamp
= get_parameter_u32 (para
, pKEYCREATIONDATE
);
3222 timestamp
= make_timestamp ();
3226 rc
= do_create (get_parameter_algo( para
, pKEYTYPE
),
3227 get_parameter_uint( para
, pKEYLENGTH
),
3229 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3230 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3233 get_parameter_u32( para
, pKEYEXPIRE
), 0 );
3237 /* Note, that depending on the backend, the card key generation
3238 may update TIMESTAMP. */
3239 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 1, 1, pub_root
, sec_root
, NULL
,
3241 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3244 pri_sk
= sec_root
->next
->pkt
->pkt
.secret_key
;
3249 if(!rc
&& (revkey
=get_parameter_revkey(para
,pREVOKER
)))
3251 rc
= write_direct_sig (pub_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3253 rc
= write_direct_sig (sec_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3256 if( !rc
&& (s
=get_parameter_value(para
, pUSERID
)) )
3258 write_uid (pub_root
, s
);
3259 write_uid (sec_root
, s
);
3261 rc
= write_selfsigs (sec_root
, pub_root
, pri_sk
,
3262 get_parameter_uint (para
, pKEYUSAGE
), timestamp
);
3265 /* Write the auth key to the card before the encryption key. This
3266 is a partial workaround for a PGP bug (as of this writing, all
3267 versions including 8.1), that causes it to try and encrypt to
3268 the most recent subkey regardless of whether that subkey is
3269 actually an encryption type. In this case, the auth key is an
3270 RSA key so it succeeds. */
3272 if (!rc
&& card
&& get_parameter (para
, pAUTHKEYTYPE
))
3274 /* Note, that depending on the backend, the card key generation
3275 may update TIMESTAMP. */
3276 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 3, 0, pub_root
, sec_root
, NULL
,
3278 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3281 rc
= write_keybinding (pub_root
, pub_root
, pri_sk
, sub_sk
,
3282 PUBKEY_USAGE_AUTH
, timestamp
);
3284 rc
= write_keybinding (sec_root
, pub_root
, pri_sk
, sub_sk
,
3285 PUBKEY_USAGE_AUTH
, timestamp
);
3288 if( !rc
&& get_parameter( para
, pSUBKEYTYPE
) )
3292 rc
= do_create( get_parameter_algo( para
, pSUBKEYTYPE
),
3293 get_parameter_uint( para
, pSUBKEYLENGTH
),
3295 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3296 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3299 get_parameter_u32( para
, pSUBKEYEXPIRE
), 1 );
3303 if ((s
= get_parameter_value (para
, pBACKUPENCDIR
)))
3305 /* A backup of the encryption key has been requested.
3306 Generate the key in software and import it then to
3307 the card. Write a backup file. */
3308 rc
= gen_card_key_with_backup (PUBKEY_ALGO_RSA
, 2, 0,
3311 get_parameter_u32 (para
,
3317 /* Note, that depending on the backend, the card key
3318 generation may update TIMESTAMP. */
3319 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 2, 0, pub_root
, sec_root
,
3322 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3327 rc
= write_keybinding(pub_root
, pub_root
, pri_sk
, sub_sk
,
3328 get_parameter_uint (para
, pSUBKEYUSAGE
),
3331 rc
= write_keybinding(sec_root
, pub_root
, pri_sk
, sub_sk
,
3332 get_parameter_uint (para
, pSUBKEYUSAGE
),
3337 if (!rc
&& outctrl
->use_files
) /* Direct write to specified files. */
3339 rc
= write_keyblock( outctrl
->pub
.stream
, pub_root
);
3341 log_error ("can't write public key: %s\n", g10_errstr(rc
) );
3344 rc
= write_keyblock( outctrl
->sec
.stream
, sec_root
);
3346 log_error ("can't write secret key: %s\n", g10_errstr(rc
) );
3349 else if (!rc
) /* Write to the standard keyrings. */
3351 KEYDB_HANDLE pub_hd
= keydb_new (0);
3352 KEYDB_HANDLE sec_hd
= keydb_new (1);
3354 rc
= keydb_locate_writable (pub_hd
, NULL
);
3356 log_error (_("no writable public keyring found: %s\n"),
3361 rc
= keydb_locate_writable (sec_hd
, NULL
);
3363 log_error (_("no writable secret keyring found: %s\n"),
3367 if (!rc
&& opt
.verbose
)
3369 log_info (_("writing public key to `%s'\n"),
3370 keydb_get_resource_name (pub_hd
));
3372 log_info (_("writing secret key stub to `%s'\n"),
3373 keydb_get_resource_name (sec_hd
));
3375 log_info (_("writing secret key to `%s'\n"),
3376 keydb_get_resource_name (sec_hd
));
3381 rc
= keydb_insert_keyblock (pub_hd
, pub_root
);
3383 log_error (_("error writing public keyring `%s': %s\n"),
3384 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3389 rc
= keydb_insert_keyblock (sec_hd
, sec_root
);
3391 log_error (_("error writing secret keyring `%s': %s\n"),
3392 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3395 keydb_release (pub_hd
);
3396 keydb_release (sec_hd
);
3403 no_enc_rsa
= (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_RSA
3404 && get_parameter_uint (para
, pKEYUSAGE
)
3405 && !((get_parameter_uint (para
, pKEYUSAGE
)
3406 & PUBKEY_USAGE_ENC
)) );
3408 pk
= find_kbnode (pub_root
, PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3410 keyid_from_pk(pk
,pk
->main_keyid
);
3411 register_trusted_keyid(pk
->main_keyid
);
3413 update_ownertrust (pk
, ((get_ownertrust (pk
) & ~TRUST_MASK
)
3414 | TRUST_ULTIMATE
));
3418 tty_printf (_("public and secret key created and signed.\n") );
3420 list_keyblock(pub_root
,0,1,NULL
);
3425 && (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_DSA
3427 && !get_parameter (para
, pSUBKEYTYPE
) )
3429 tty_printf(_("Note that this key cannot be used for "
3430 "encryption. You may want to use\n"
3431 "the command \"--edit-key\" to generate a "
3432 "subkey for this purpose.\n") );
3440 log_error ("key generation failed: %s\n", g10_errstr(rc
) );
3442 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3443 print_status_key_not_created ( get_parameter_value (para
, pHANDLE
) );
3447 PKT_public_key
*pk
= find_kbnode (pub_root
,
3448 PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3449 print_status_key_created (did_sub
? 'B':'P', pk
,
3450 get_parameter_value (para
, pHANDLE
));
3452 release_kbnode( pub_root
);
3453 release_kbnode( sec_root
);
3455 if (pri_sk
&& !card
) /* The unprotected secret key unless we */
3456 free_secret_key (pri_sk
); /* have a shallow copy in card mode. */
3458 free_secret_key(sub_sk
);
3462 /* Add a new subkey to an existing key. Returns true if a new key has
3463 been generated and put into the keyblocks. */
3465 generate_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
)
3469 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3474 char *passphrase
= NULL
;
3476 STRING2KEY
*s2k
= NULL
;
3481 /* Break out the primary secret key. */
3482 node
= find_kbnode( sec_keyblock
, PKT_SECRET_KEY
);
3485 log_error ("Oops; secret key not found anymore!\n");
3489 /* Make a copy of the sk to keep the protected one in the keyblock. */
3490 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3492 cur_time
= make_timestamp();
3494 if (pri_sk
->timestamp
> cur_time
)
3496 ulong d
= pri_sk
->timestamp
- cur_time
;
3497 log_info ( d
==1 ? _("key has been created %lu second "
3498 "in future (time warp or clock problem)\n")
3499 : _("key has been created %lu seconds "
3500 "in future (time warp or clock problem)\n"), d
);
3501 if (!opt
.ignore_time_conflict
)
3503 rc
= G10ERR_TIME_CONFLICT
;
3508 if (pri_sk
->version
< 4)
3510 log_info (_("NOTE: creating subkeys for v3 keys "
3511 "is not OpenPGP compliant\n"));
3515 if (pri_sk
->is_protected
&& pri_sk
->protect
.s2k
.mode
== 1001)
3517 tty_printf (_("Secret parts of primary key are not available.\n"));
3518 rc
= G10ERR_NO_SECKEY
;
3523 /* Unprotect to get the passphrase. */
3524 switch (is_secret_key_protected (pri_sk
) )
3527 rc
= G10ERR_PUBKEY_ALGO
;
3530 tty_printf (_("This key is not protected.\n"));
3533 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3537 tty_printf (_("Key is protected.\n"));
3538 rc
= check_secret_key ( pri_sk
, 0 );
3540 passphrase
= get_last_passphrase();
3546 algo
= ask_algo (1, &use
);
3548 nbits
= ask_keysize (algo
);
3549 expire
= ask_expire_interval (0, NULL
);
3550 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3551 _("Really create? (y/N) ")))
3556 dek
= do_ask_passphrase (&s2k
, &canceled
);
3557 else if (passphrase
)
3559 s2k
= xmalloc_secure ( sizeof *s2k
);
3560 s2k
->mode
= opt
.s2k_mode
;
3561 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
3562 set_next_passphrase ( passphrase
);
3563 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
3568 rc
= GPG_ERR_CANCELED
;
3571 rc
= do_create (algo
, nbits
, pub_keyblock
, sec_keyblock
,
3572 dek
, s2k
, &sub_sk
, cur_time
, expire
, 1 );
3574 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3577 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3582 write_status_text (STATUS_KEY_CREATED
, "S");
3587 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3591 /* Release the copy of the (now unprotected) secret keys. */
3593 free_secret_key (pri_sk
);
3595 free_secret_key (sub_sk
);
3596 set_next_passphrase (NULL
);
3601 #ifdef ENABLE_CARD_SUPPORT
3602 /* Generate a subkey on a card. */
3604 generate_card_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
,
3605 int keyno
, const char *serialno
)
3609 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
;
3613 char *passphrase
= NULL
;
3615 struct para_data_s
*para
= NULL
;
3617 assert (keyno
>= 1 && keyno
<= 3);
3619 para
= xcalloc (1, sizeof *para
+ strlen (serialno
) );
3620 para
->key
= pSERIALNO
;
3621 strcpy (para
->u
.value
, serialno
);
3623 /* Break out the primary secret key */
3624 node
= find_kbnode (sec_keyblock
, PKT_SECRET_KEY
);
3627 log_error("Oops; secret key not found anymore!\n");
3631 /* Make a copy of the sk to keep the protected one in the keyblock */
3632 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3634 cur_time
= make_timestamp();
3635 if (pri_sk
->timestamp
> cur_time
)
3637 ulong d
= pri_sk
->timestamp
- cur_time
;
3638 log_info (d
==1 ? _("key has been created %lu second "
3639 "in future (time warp or clock problem)\n")
3640 : _("key has been created %lu seconds "
3641 "in future (time warp or clock problem)\n"), d
);
3642 if (!opt
.ignore_time_conflict
)
3644 rc
= G10ERR_TIME_CONFLICT
;
3649 if (pri_sk
->version
< 4)
3651 log_info (_("NOTE: creating subkeys for v3 keys "
3652 "is not OpenPGP compliant\n"));
3656 /* Unprotect to get the passphrase. */
3657 switch( is_secret_key_protected (pri_sk
) )
3660 rc
= G10ERR_PUBKEY_ALGO
;
3663 tty_printf("This key is not protected.\n");
3666 tty_printf("Key is protected.\n");
3667 rc
= check_secret_key( pri_sk
, 0 );
3669 passphrase
= get_last_passphrase();
3675 algo
= PUBKEY_ALGO_RSA
;
3676 expire
= ask_expire_interval (0,NULL
);
3678 use
= PUBKEY_USAGE_SIG
;
3679 else if (keyno
== 2)
3680 use
= PUBKEY_USAGE_ENC
;
3682 use
= PUBKEY_USAGE_AUTH
;
3683 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3684 _("Really create? (y/N) ")))
3688 set_next_passphrase (passphrase
);
3690 /* Note, that depending on the backend, the card key generation may
3692 rc
= gen_card_key (algo
, keyno
, 0, pub_keyblock
, sec_keyblock
,
3693 &sub_sk
, &cur_time
, expire
, para
);
3695 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3698 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3703 write_status_text (STATUS_KEY_CREATED
, "S");
3708 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3710 /* Release the copy of the (now unprotected) secret keys. */
3712 free_secret_key (pri_sk
);
3713 set_next_passphrase( NULL
);
3714 release_parameter_list (para
);
3717 #endif /* !ENABLE_CARD_SUPPORT */
3721 * Write a keyblock to an output stream
3724 write_keyblock( IOBUF out
, KBNODE node
)
3726 for( ; node
; node
= node
->next
)
3728 if(!is_deleted_kbnode(node
))
3730 int rc
= build_packet( out
, node
->pkt
);
3733 log_error("build_packet(%d) failed: %s\n",
3734 node
->pkt
->pkttype
, g10_errstr(rc
) );
3744 /* Note that timestamp is an in/out arg. */
3746 gen_card_key (int algo
, int keyno
, int is_primary
,
3747 KBNODE pub_root
, KBNODE sec_root
, PKT_secret_key
**ret_sk
,
3748 u32
*timestamp
, u32 expireval
, struct para_data_s
*para
)
3750 #ifdef ENABLE_CARD_SUPPORT
3753 struct agent_card_genkey_s info
;
3758 assert (algo
== PUBKEY_ALGO_RSA
);
3760 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3761 rc
= agent_scd_genkey (&info
, keyno
, 1, NULL
, *timestamp
);
3762 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3764 /* tty_printf ("\n"); */
3765 /* log_error ("WARNING: key does already exists!\n"); */
3766 /* tty_printf ("\n"); */
3767 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3768 /* _("Replace existing key? "))) */
3769 /* rc = agent_scd_genkey (&info, keyno, 1); */
3774 log_error ("key generation failed: %s\n", gpg_strerror (rc
));
3777 if ( !info
.n
|| !info
.e
)
3779 log_error ("communication error with SCD\n");
3780 gcry_mpi_release (info
.n
);
3781 gcry_mpi_release (info
.e
);
3782 return gpg_error (GPG_ERR_GENERAL
);
3785 if (*timestamp
!= info
.created_at
)
3786 log_info ("Note that the key does not use the suggested creation date\n");
3787 *timestamp
= info
.created_at
;
3789 pk
= xcalloc (1, sizeof *pk
);
3790 sk
= xcalloc (1, sizeof *sk
);
3791 sk
->timestamp
= pk
->timestamp
= info
.created_at
;
3792 sk
->version
= pk
->version
= 4;
3794 sk
->expiredate
= pk
->expiredate
= pk
->timestamp
+ expireval
;
3795 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
3796 pk
->pkey
[0] = info
.n
;
3797 pk
->pkey
[1] = info
.e
;
3798 sk
->skey
[0] = gcry_mpi_copy (pk
->pkey
[0]);
3799 sk
->skey
[1] = gcry_mpi_copy (pk
->pkey
[1]);
3800 sk
->skey
[2] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3801 sk
->is_protected
= 1;
3802 sk
->protect
.s2k
.mode
= 1002;
3803 s
= get_parameter_value (para
, pSERIALNO
);
3806 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
3807 sk
->protect
.ivlen
++, s
+= 2)
3808 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
3814 pkt
= xcalloc (1,sizeof *pkt
);
3815 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
3816 pkt
->pkt
.public_key
= pk
;
3817 add_kbnode(pub_root
, new_kbnode( pkt
));
3819 pkt
= xcalloc (1,sizeof *pkt
);
3820 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
3821 pkt
->pkt
.secret_key
= sk
;
3822 add_kbnode(sec_root
, new_kbnode( pkt
));
3827 #endif /*!ENABLE_CARD_SUPPORT*/
3833 gen_card_key_with_backup (int algo
, int keyno
, int is_primary
,
3834 KBNODE pub_root
, KBNODE sec_root
,
3836 u32 expireval
, struct para_data_s
*para
,
3837 const char *backup_dir
)
3839 #ifdef ENABLE_CARD_SUPPORT
3843 PKT_secret_key
*sk
, *sk_unprotected
= NULL
, *sk_protected
= NULL
;
3848 rc
= generate_raw_key (algo
, 1024, timestamp
,
3849 &sk_unprotected
, &sk_protected
);
3853 /* First, store the key to the card. */
3854 rc
= save_unprotected_key_to_card (sk_unprotected
, keyno
);
3857 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc
));
3858 free_secret_key (sk_unprotected
);
3859 free_secret_key (sk_protected
);
3863 /* Get rid of the secret key parameters and store the serial numer. */
3864 sk
= sk_unprotected
;
3865 n
= pubkey_get_nskey (sk
->pubkey_algo
);
3866 for (i
=pubkey_get_npkey (sk
->pubkey_algo
); i
< n
; i
++)
3868 gcry_mpi_release (sk
->skey
[i
]);
3871 i
= pubkey_get_npkey (sk
->pubkey_algo
);
3872 sk
->skey
[i
] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3873 sk
->is_protected
= 1;
3874 sk
->protect
.s2k
.mode
= 1002;
3875 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
);
3881 /* Now write the *protected* secret key to the file. */
3883 char name_buffer
[50];
3888 keyid_from_sk (sk
, NULL
);
3889 sprintf (name_buffer
,"sk_%08lX%08lX.gpg",
3890 (ulong
)sk
->keyid
[0], (ulong
)sk
->keyid
[1]);
3892 fname
= make_filename (backup_dir
, name_buffer
, NULL
);
3893 oldmask
= umask (077);
3894 if (is_secured_filename (fname
))
3900 fp
= iobuf_create (fname
);
3904 rc
= gpg_error_from_syserror ();
3905 log_error (_("can't create backup file `%s': %s\n"),
3906 fname
, strerror(errno
) );
3908 free_secret_key (sk_unprotected
);
3909 free_secret_key (sk_protected
);
3913 pkt
= xcalloc (1, sizeof *pkt
);
3914 pkt
->pkttype
= PKT_SECRET_KEY
;
3915 pkt
->pkt
.secret_key
= sk_protected
;
3916 sk_protected
= NULL
;
3918 rc
= build_packet (fp
, pkt
);
3921 log_error("build packet failed: %s\n", g10_errstr(rc
) );
3926 unsigned char array
[MAX_FINGERPRINT_LEN
];
3930 iobuf_ioctl (NULL
, 2, 0, (char*)fname
);
3931 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname
);
3933 fingerprint_from_sk (sk
, array
, &n
);
3934 p
= fprbuf
= xmalloc (MAX_FINGERPRINT_LEN
*2 + 1 + 1);
3935 for (i
=0; i
< n
; i
++, p
+= 2)
3936 sprintf (p
, "%02X", array
[i
]);
3940 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED
,
3942 fname
, strlen (fname
),
3951 free_secret_key (sk_unprotected
);
3956 /* Create the public key from the secret key. */
3957 pk
= xcalloc (1, sizeof *pk
);
3958 pk
->timestamp
= sk
->timestamp
;
3959 pk
->version
= sk
->version
;
3961 pk
->expiredate
= sk
->expiredate
= sk
->timestamp
+ expireval
;
3962 pk
->pubkey_algo
= sk
->pubkey_algo
;
3963 n
= pubkey_get_npkey (sk
->pubkey_algo
);
3964 for (i
=0; i
< n
; i
++)
3965 pk
->pkey
[i
] = mpi_copy (sk
->skey
[i
]);
3967 /* Build packets and add them to the node lists. */
3968 pkt
= xcalloc (1,sizeof *pkt
);
3969 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
3970 pkt
->pkt
.public_key
= pk
;
3971 add_kbnode(pub_root
, new_kbnode( pkt
));
3973 pkt
= xcalloc (1,sizeof *pkt
);
3974 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
3975 pkt
->pkt
.secret_key
= sk
;
3976 add_kbnode(sec_root
, new_kbnode( pkt
));
3981 #endif /*!ENABLE_CARD_SUPPORT*/
3985 #ifdef ENABLE_CARD_SUPPORT
3987 save_unprotected_key_to_card (PKT_secret_key
*sk
, int keyno
)
3990 unsigned char *rsa_n
= NULL
;
3991 unsigned char *rsa_e
= NULL
;
3992 unsigned char *rsa_p
= NULL
;
3993 unsigned char *rsa_q
= NULL
;
3994 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
3995 unsigned char *sexp
= NULL
;
3997 char numbuf
[55], numbuf2
[50];
3999 assert (is_RSA (sk
->pubkey_algo
));
4000 assert (!sk
->is_protected
);
4002 /* Copy the parameters into straight buffers. */
4003 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_n
, &rsa_n_len
, sk
->skey
[0]);
4004 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_e
, &rsa_e_len
, sk
->skey
[1]);
4005 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_p
, &rsa_p_len
, sk
->skey
[3]);
4006 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_q
, &rsa_q_len
, sk
->skey
[4]);
4007 if (!rsa_n
|| !rsa_e
|| !rsa_p
|| !rsa_q
)
4009 rc
= G10ERR_INV_ARG
;
4013 /* Put the key into an S-expression. */
4014 sexp
= p
= xmalloc_secure (30
4015 + rsa_n_len
+ rsa_e_len
+ rsa_p_len
+ rsa_q_len
4016 + 4*sizeof (numbuf
) + 25 + sizeof(numbuf
) + 20);
4018 p
= stpcpy (p
,"(11:private-key(3:rsa(1:n");
4019 sprintf (numbuf
, "%u:", (unsigned int)rsa_n_len
);
4020 p
= stpcpy (p
, numbuf
);
4021 memcpy (p
, rsa_n
, rsa_n_len
);
4024 sprintf (numbuf
, ")(1:e%u:", (unsigned int)rsa_e_len
);
4025 p
= stpcpy (p
, numbuf
);
4026 memcpy (p
, rsa_e
, rsa_e_len
);
4029 sprintf (numbuf
, ")(1:p%u:", (unsigned int)rsa_p_len
);
4030 p
= stpcpy (p
, numbuf
);
4031 memcpy (p
, rsa_p
, rsa_p_len
);
4034 sprintf (numbuf
, ")(1:q%u:", (unsigned int)rsa_q_len
);
4035 p
= stpcpy (p
, numbuf
);
4036 memcpy (p
, rsa_q
, rsa_q_len
);
4039 p
= stpcpy (p
,"))(10:created-at");
4040 sprintf (numbuf2
, "%lu", (unsigned long)sk
->timestamp
);
4041 sprintf (numbuf
, "%lu:", (unsigned long)strlen (numbuf2
));
4042 p
= stpcpy (stpcpy (stpcpy (p
, numbuf
), numbuf2
), "))");
4044 /* Fixme: Unfortunately we don't have the serialnumber available -
4045 thus we can't pass it down to the agent. */
4046 rc
= agent_scd_writekey (keyno
, NULL
, sexp
, p
- sexp
);
4056 #endif /*ENABLE_CARD_SUPPORT*/