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. Returns -1 on
2291 * error, 0 for no usage given or 1 for usage available.
2294 parse_parameter_usage (const char *fname
,
2295 struct para_data_s
*para
, enum para_name key
)
2297 struct para_data_s
*r
= get_parameter( para
, key
);
2302 return 0; /* none (this is an optional parameter)*/
2306 while ( (p
= strsep (&pn
, " \t,")) ) {
2309 else if ( !ascii_strcasecmp (p
, "sign") )
2310 use
|= PUBKEY_USAGE_SIG
;
2311 else if ( !ascii_strcasecmp (p
, "encrypt") )
2312 use
|= PUBKEY_USAGE_ENC
;
2313 else if ( !ascii_strcasecmp (p
, "auth") )
2314 use
|= PUBKEY_USAGE_AUTH
;
2316 log_error("%s:%d: invalid usage list\n", fname
, r
->lnr
);
2317 return -1; /* error */
2325 parse_revocation_key (const char *fname
,
2326 struct para_data_s
*para
, enum para_name key
)
2328 struct para_data_s
*r
= get_parameter( para
, key
);
2329 struct revocation_key revkey
;
2334 return 0; /* none (this is an optional parameter) */
2339 revkey
.algid
=atoi(pn
);
2343 /* Skip to the fpr */
2344 while(*pn
&& *pn
!=':')
2352 for(i
=0;i
<MAX_FINGERPRINT_LEN
&& *pn
;i
++,pn
+=2)
2354 int c
=hextobyte(pn
);
2361 /* skip to the tag */
2362 while(*pn
&& *pn
!='s' && *pn
!='S')
2365 if(ascii_strcasecmp(pn
,"sensitive")==0)
2368 memcpy(&r
->u
.revkey
,&revkey
,sizeof(struct revocation_key
));
2373 log_error("%s:%d: invalid revocation key\n", fname
, r
->lnr
);
2374 return -1; /* error */
2379 get_parameter_u32( struct para_data_s
*para
, enum para_name key
)
2381 struct para_data_s
*r
= get_parameter( para
, key
);
2385 if( r
->key
== pKEYCREATIONDATE
)
2386 return r
->u
.creation
;
2387 if( r
->key
== pKEYEXPIRE
|| r
->key
== pSUBKEYEXPIRE
)
2389 if( r
->key
== pKEYUSAGE
|| r
->key
== pSUBKEYUSAGE
)
2392 return (unsigned int)strtoul( r
->u
.value
, NULL
, 10 );
2396 get_parameter_uint( struct para_data_s
*para
, enum para_name key
)
2398 return get_parameter_u32( para
, key
);
2402 get_parameter_dek( struct para_data_s
*para
, enum para_name key
)
2404 struct para_data_s
*r
= get_parameter( para
, key
);
2405 return r
? r
->u
.dek
: NULL
;
2409 get_parameter_s2k( struct para_data_s
*para
, enum para_name key
)
2411 struct para_data_s
*r
= get_parameter( para
, key
);
2412 return r
? r
->u
.s2k
: NULL
;
2415 static struct revocation_key
*
2416 get_parameter_revkey( struct para_data_s
*para
, enum para_name key
)
2418 struct para_data_s
*r
= get_parameter( para
, key
);
2419 return r
? &r
->u
.revkey
: NULL
;
2423 proc_parameter_file( struct para_data_s
*para
, const char *fname
,
2424 struct output_control_s
*outctrl
, int card
)
2426 struct para_data_s
*r
;
2427 const char *s1
, *s2
, *s3
;
2430 int have_user_id
=0,err
,algo
;
2432 /* Check that we have all required parameters. */
2433 r
= get_parameter( para
, pKEYTYPE
);
2436 algo
=get_parameter_algo(para
,pKEYTYPE
);
2437 if (openpgp_pk_test_algo2 (algo
, PUBKEY_USAGE_SIG
))
2439 log_error ("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2445 log_error ("%s: no Key-Type specified\n",fname
);
2449 err
= parse_parameter_usage (fname
, para
, pKEYUSAGE
);
2452 /* Default to algo capabilities if key-usage is not provided */
2453 r
= xmalloc_clear(sizeof(*r
));
2455 r
->u
.usage
= openpgp_pk_algo_usage(algo
);
2463 r
= get_parameter (para
, pKEYUSAGE
);
2464 if (r
&& (r
->u
.usage
& ~openpgp_pk_algo_usage (algo
)))
2466 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2467 fname
, r
->lnr
, algo
);
2472 r
= get_parameter( para
, pSUBKEYTYPE
);
2475 algo
= get_parameter_algo (para
, pSUBKEYTYPE
);
2476 if (openpgp_pk_test_algo (algo
))
2478 log_error ("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2482 err
= parse_parameter_usage (fname
, para
, pSUBKEYUSAGE
);
2485 /* Default to algo capabilities if subkey-usage is not
2487 r
= xmalloc_clear (sizeof(*r
));
2488 r
->key
= pSUBKEYUSAGE
;
2489 r
->u
.usage
= openpgp_pk_algo_usage (algo
);
2497 r
= get_parameter (para
, pSUBKEYUSAGE
);
2498 if (r
&& (r
->u
.usage
& ~openpgp_pk_algo_usage (algo
)))
2500 log_error ("%s:%d: specified Subkey-Usage not allowed"
2501 " for algo %d\n", fname
, r
->lnr
, algo
);
2508 if( get_parameter_value( para
, pUSERID
) )
2512 /* create the formatted user ID */
2513 s1
= get_parameter_value( para
, pNAMEREAL
);
2514 s2
= get_parameter_value( para
, pNAMECOMMENT
);
2515 s3
= get_parameter_value( para
, pNAMEEMAIL
);
2516 if( s1
|| s2
|| s3
)
2518 n
= (s1
?strlen(s1
):0) + (s2
?strlen(s2
):0) + (s3
?strlen(s3
):0);
2519 r
= xmalloc_clear( sizeof *r
+ n
+ 20 );
2525 p
= stpcpy(stpcpy(stpcpy(p
," ("), s2
),")");
2527 p
= stpcpy(stpcpy(stpcpy(p
," <"), s3
),">");
2536 log_error("%s: no User-ID specified\n",fname
);
2540 /* Set preferences, if any. */
2541 keygen_set_std_prefs(get_parameter_value( para
, pPREFERENCES
), 0);
2543 /* Set keyserver, if any. */
2544 s1
=get_parameter_value( para
, pKEYSERVER
);
2547 struct keyserver_spec
*spec
;
2549 spec
=parse_keyserver_uri(s1
,1,NULL
,0);
2552 free_keyserver_spec(spec
);
2553 opt
.def_keyserver_url
=s1
;
2557 log_error("%s:%d: invalid keyserver url\n", fname
, r
->lnr
);
2562 /* Set revoker, if any. */
2563 if (parse_revocation_key (fname
, para
, pREVOKER
))
2566 /* Make DEK and S2K from the Passphrase. */
2567 if (outctrl
->ask_passphrase
)
2569 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2570 feature is required so that GUIs are able to do a key
2571 creation but have gpg-agent ask for the passphrase. */
2576 dek
= do_ask_passphrase ( &s2k
, &canceled
);
2579 r
= xmalloc_clear( sizeof *r
);
2580 r
->key
= pPASSPHRASE_DEK
;
2584 r
= xmalloc_clear( sizeof *r
);
2585 r
->key
= pPASSPHRASE_S2K
;
2593 log_error ("%s:%d: key generation canceled\n", fname
, r
->lnr
);
2599 r
= get_parameter( para
, pPASSPHRASE
);
2600 if ( r
&& *r
->u
.value
)
2602 /* We have a plain text passphrase - create a DEK from it.
2603 * It is a little bit ridiculous to keep it in secure memory
2604 * but because we do this always, why not here. */
2608 s2k
= xmalloc_secure ( sizeof *s2k
);
2609 s2k
->mode
= opt
.s2k_mode
;
2610 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2611 set_next_passphrase ( r
->u
.value
);
2612 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2614 set_next_passphrase (NULL
);
2616 memset (r
->u
.value
, 0, strlen(r
->u
.value
));
2618 r
= xmalloc_clear (sizeof *r
);
2619 r
->key
= pPASSPHRASE_S2K
;
2623 r
= xmalloc_clear (sizeof *r
);
2624 r
->key
= pPASSPHRASE_DEK
;
2631 /* Make KEYCREATIONDATE from Creation-Date. */
2632 r
= get_parameter (para
, pCREATIONDATE
);
2633 if (r
&& *r
->u
.value
)
2637 seconds
= parse_creation_string (r
->u
.value
);
2640 log_error ("%s:%d: invalid creation date\n", fname
, r
->lnr
);
2643 r
->u
.creation
= seconds
;
2644 r
->key
= pKEYCREATIONDATE
; /* Change that entry. */
2647 /* Make KEYEXPIRE from Expire-Date. */
2648 r
= get_parameter( para
, pEXPIREDATE
);
2649 if( r
&& *r
->u
.value
)
2653 seconds
= parse_expire_string( r
->u
.value
);
2654 if( seconds
== (u32
)-1 )
2656 log_error("%s:%d: invalid expire date\n", fname
, r
->lnr
);
2659 r
->u
.expire
= seconds
;
2660 r
->key
= pKEYEXPIRE
; /* change hat entry */
2661 /* also set it for the subkey */
2662 r
= xmalloc_clear( sizeof *r
+ 20 );
2663 r
->key
= pSUBKEYEXPIRE
;
2664 r
->u
.expire
= seconds
;
2669 if( !!outctrl
->pub
.newfname
^ !!outctrl
->sec
.newfname
) {
2670 log_error("%s:%d: only one ring name is set\n", fname
, outctrl
->lnr
);
2674 do_generate_keypair( para
, outctrl
, card
);
2680 * Kludge to allow non interactive key generation controlled
2681 * by a parameter file.
2682 * Note, that string parameters are expected to be in UTF-8
2685 read_parameter_file( const char *fname
)
2687 static struct { const char *name
;
2690 { "Key-Type", pKEYTYPE
},
2691 { "Key-Length", pKEYLENGTH
},
2692 { "Key-Usage", pKEYUSAGE
},
2693 { "Subkey-Type", pSUBKEYTYPE
},
2694 { "Subkey-Length", pSUBKEYLENGTH
},
2695 { "Subkey-Usage", pSUBKEYUSAGE
},
2696 { "Name-Real", pNAMEREAL
},
2697 { "Name-Email", pNAMEEMAIL
},
2698 { "Name-Comment", pNAMECOMMENT
},
2699 { "Expire-Date", pEXPIREDATE
},
2700 { "Creation-Date", pCREATIONDATE
},
2701 { "Passphrase", pPASSPHRASE
},
2702 { "Preferences", pPREFERENCES
},
2703 { "Revoker", pREVOKER
},
2704 { "Handle", pHANDLE
},
2705 { "Keyserver", pKEYSERVER
},
2710 unsigned int maxlen
, nline
;
2713 const char *err
= NULL
;
2714 struct para_data_s
*para
, *r
;
2716 struct output_control_s outctrl
;
2718 memset( &outctrl
, 0, sizeof( outctrl
) );
2719 outctrl
.pub
.afx
= new_armor_context ();
2720 outctrl
.sec
.afx
= new_armor_context ();
2722 if( !fname
|| !*fname
)
2725 fp
= iobuf_open (fname
);
2726 if (fp
&& is_secured_file (iobuf_get_fd (fp
)))
2733 log_error (_("can't open `%s': %s\n"), fname
, strerror(errno
) );
2736 iobuf_ioctl (fp
, 3, 1, NULL
); /* No file caching. */
2743 while ( iobuf_read_line (fp
, &line
, &nline
, &maxlen
) ) {
2744 char *keyword
, *value
;
2748 err
= "line too long";
2751 for( p
= line
; isspace(*(byte
*)p
); p
++ )
2753 if( !*p
|| *p
== '#' )
2756 if( *keyword
== '%' ) {
2757 for( ; !isspace(*(byte
*)p
); p
++ )
2761 for( ; isspace(*(byte
*)p
); p
++ )
2764 trim_trailing_ws( value
, strlen(value
) );
2765 if( !ascii_strcasecmp( keyword
, "%echo" ) )
2766 log_info("%s\n", value
);
2767 else if( !ascii_strcasecmp( keyword
, "%dry-run" ) )
2769 else if( !ascii_strcasecmp( keyword
, "%ask-passphrase" ) )
2770 outctrl
.ask_passphrase
= 1;
2771 else if( !ascii_strcasecmp( keyword
, "%no-ask-passphrase" ) )
2772 outctrl
.ask_passphrase
= 0;
2773 else if( !ascii_strcasecmp( keyword
, "%commit" ) ) {
2775 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2776 print_status_key_not_created
2777 (get_parameter_value (para
, pHANDLE
));
2778 release_parameter_list( para
);
2781 else if( !ascii_strcasecmp( keyword
, "%pubring" ) ) {
2782 if( outctrl
.pub
.fname
&& !strcmp( outctrl
.pub
.fname
, value
) )
2783 ; /* still the same file - ignore it */
2785 xfree( outctrl
.pub
.newfname
);
2786 outctrl
.pub
.newfname
= xstrdup( value
);
2787 outctrl
.use_files
= 1;
2790 else if( !ascii_strcasecmp( keyword
, "%secring" ) ) {
2791 if( outctrl
.sec
.fname
&& !strcmp( outctrl
.sec
.fname
, value
) )
2792 ; /* still the same file - ignore it */
2794 xfree( outctrl
.sec
.newfname
);
2795 outctrl
.sec
.newfname
= xstrdup( value
);
2796 outctrl
.use_files
= 1;
2800 log_info("skipping control `%s' (%s)\n", keyword
, value
);
2807 if( !(p
= strchr( p
, ':' )) || p
== keyword
) {
2808 err
= "missing colon";
2813 for( ; isspace(*(byte
*)p
); p
++ )
2816 err
= "missing argument";
2820 trim_trailing_ws( value
, strlen(value
) );
2822 for(i
=0; keywords
[i
].name
; i
++ ) {
2823 if( !ascii_strcasecmp( keywords
[i
].name
, keyword
) )
2826 if( !keywords
[i
].name
) {
2827 err
= "unknown keyword";
2830 if( keywords
[i
].key
!= pKEYTYPE
&& !para
) {
2831 err
= "parameter block does not start with \"Key-Type\"";
2835 if( keywords
[i
].key
== pKEYTYPE
&& para
) {
2837 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2838 print_status_key_not_created
2839 (get_parameter_value (para
, pHANDLE
));
2840 release_parameter_list( para
);
2844 for( r
= para
; r
; r
= r
->next
) {
2845 if( r
->key
== keywords
[i
].key
)
2849 err
= "duplicate keyword";
2853 r
= xmalloc_clear( sizeof *r
+ strlen( value
) );
2855 r
->key
= keywords
[i
].key
;
2856 strcpy( r
->u
.value
, value
);
2861 log_error("%s:%d: %s\n", fname
, lnr
, err
);
2862 else if( iobuf_error (fp
) ) {
2863 log_error("%s:%d: read error\n", fname
, lnr
);
2867 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2868 print_status_key_not_created (get_parameter_value (para
, pHANDLE
));
2871 if( outctrl
.use_files
) { /* close open streams */
2872 iobuf_close( outctrl
.pub
.stream
);
2873 iobuf_close( outctrl
.sec
.stream
);
2875 /* Must invalidate that ugly cache to actually close it. */
2876 if (outctrl
.pub
.fname
)
2877 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.pub
.fname
);
2878 if (outctrl
.sec
.fname
)
2879 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.sec
.fname
);
2881 xfree( outctrl
.pub
.fname
);
2882 xfree( outctrl
.pub
.newfname
);
2883 xfree( outctrl
.sec
.fname
);
2884 xfree( outctrl
.sec
.newfname
);
2887 release_parameter_list( para
);
2889 release_armor_context (outctrl
.pub
.afx
);
2890 release_armor_context (outctrl
.sec
.afx
);
2895 * Generate a keypair (fname is only used in batch mode) If
2896 * CARD_SERIALNO is not NULL the function will create the keys on an
2897 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2898 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2899 * generate in software, imported to the card and a backup file
2900 * written to directory given by this argument .
2903 generate_keypair (const char *fname
, const char *card_serialno
,
2904 const char *backup_encryption_dir
)
2914 struct para_data_s
*para
= NULL
;
2915 struct para_data_s
*r
;
2916 struct output_control_s outctrl
;
2919 memset( &outctrl
, 0, sizeof( outctrl
) );
2921 if (opt
.batch
&& card_serialno
)
2923 /* We don't yet support unattended key generation. */
2924 log_error (_("can't do this in batch mode\n"));
2930 read_parameter_file( fname
);
2936 #ifdef ENABLE_CARD_SUPPORT
2937 r
= xcalloc (1, sizeof *r
+ strlen (card_serialno
) );
2939 strcpy( r
->u
.value
, card_serialno
);
2943 algo
= PUBKEY_ALGO_RSA
;
2945 r
= xcalloc (1, sizeof *r
+ 20 );
2947 sprintf( r
->u
.value
, "%d", algo
);
2950 r
= xcalloc (1, sizeof *r
+ 20 );
2952 strcpy (r
->u
.value
, "sign");
2956 r
= xcalloc (1, sizeof *r
+ 20 );
2957 r
->key
= pSUBKEYTYPE
;
2958 sprintf( r
->u
.value
, "%d", algo
);
2961 r
= xcalloc (1, sizeof *r
+ 20 );
2962 r
->key
= pSUBKEYUSAGE
;
2963 strcpy (r
->u
.value
, "encrypt");
2967 r
= xcalloc (1, sizeof *r
+ 20 );
2968 r
->key
= pAUTHKEYTYPE
;
2969 sprintf( r
->u
.value
, "%d", algo
);
2973 if (backup_encryption_dir
)
2975 r
= xcalloc (1, sizeof *r
+ strlen (backup_encryption_dir
) );
2976 r
->key
= pBACKUPENCDIR
;
2977 strcpy (r
->u
.value
, backup_encryption_dir
);
2981 #endif /*ENABLE_CARD_SUPPORT*/
2985 algo
= ask_algo( 0, &use
);
2987 { /* default: DSA with ElG subkey of the specified size */
2989 r
= xmalloc_clear( sizeof *r
+ 20 );
2991 sprintf( r
->u
.value
, "%d", PUBKEY_ALGO_DSA
);
2994 nbits
= ask_keysize( PUBKEY_ALGO_DSA
);
2995 r
= xmalloc_clear( sizeof *r
+ 20 );
2996 r
->key
= pKEYLENGTH
;
2997 sprintf( r
->u
.value
, "%u", nbits
);
3000 r
= xmalloc_clear( sizeof *r
+ 20 );
3002 strcpy( r
->u
.value
, "sign" );
3006 algo
= PUBKEY_ALGO_ELGAMAL_E
;
3007 r
= xmalloc_clear( sizeof *r
+ 20 );
3008 r
->key
= pSUBKEYTYPE
;
3009 sprintf( r
->u
.value
, "%d", algo
);
3012 r
= xmalloc_clear( sizeof *r
+ 20 );
3013 r
->key
= pSUBKEYUSAGE
;
3014 strcpy( r
->u
.value
, "encrypt" );
3020 r
= xmalloc_clear( sizeof *r
+ 20 );
3022 sprintf( r
->u
.value
, "%d", algo
);
3028 r
= xmalloc_clear( sizeof *r
+ 25 );
3030 sprintf( r
->u
.value
, "%s%s%s",
3031 (use
& PUBKEY_USAGE_SIG
)? "sign ":"",
3032 (use
& PUBKEY_USAGE_ENC
)? "encrypt ":"",
3033 (use
& PUBKEY_USAGE_AUTH
)? "auth":"" );
3040 nbits
= ask_keysize( algo
);
3041 r
= xmalloc_clear( sizeof *r
+ 20 );
3042 r
->key
= both
? pSUBKEYLENGTH
: pKEYLENGTH
;
3043 sprintf( r
->u
.value
, "%u", nbits
);
3048 expire
= ask_expire_interval(0,NULL
);
3049 r
= xmalloc_clear( sizeof *r
+ 20 );
3050 r
->key
= pKEYEXPIRE
;
3051 r
->u
.expire
= expire
;
3054 r
= xmalloc_clear( sizeof *r
+ 20 );
3055 r
->key
= pSUBKEYEXPIRE
;
3056 r
->u
.expire
= expire
;
3060 uid
= ask_user_id(0);
3063 log_error(_("Key generation canceled.\n"));
3064 release_parameter_list( para
);
3067 r
= xmalloc_clear( sizeof *r
+ strlen(uid
) );
3069 strcpy( r
->u
.value
, uid
);
3074 dek
= card_serialno
? NULL
: do_ask_passphrase ( &s2k
, &canceled
);
3077 r
= xmalloc_clear( sizeof *r
);
3078 r
->key
= pPASSPHRASE_DEK
;
3082 r
= xmalloc_clear( sizeof *r
);
3083 r
->key
= pPASSPHRASE_S2K
;
3090 log_error (_("Key generation canceled.\n"));
3092 proc_parameter_file( para
, "[internal]", &outctrl
, !!card_serialno
);
3093 release_parameter_list( para
);
3097 #ifdef ENABLE_CARD_SUPPORT
3098 /* Generate a raw key and return it as a secret key packet. The
3099 function will ask for the passphrase and return a protected as well
3100 as an unprotected copy of a new secret key packet. 0 is returned
3101 on success and the caller must then free the returned values. */
3103 generate_raw_key (int algo
, unsigned int nbits
, u32 created_at
,
3104 PKT_secret_key
**r_sk_unprotected
,
3105 PKT_secret_key
**r_sk_protected
)
3109 STRING2KEY
*s2k
= NULL
;
3110 PKT_secret_key
*sk
= NULL
;
3112 size_t nskey
, npkey
;
3113 gcry_sexp_t s_parms
, s_key
;
3116 npkey
= pubkey_get_npkey (algo
);
3117 nskey
= pubkey_get_nskey (algo
);
3118 assert (nskey
<= PUBKEY_MAX_NSKEY
&& npkey
< nskey
);
3123 log_info (_("keysize invalid; using %u bits\n"), nbits
);
3128 nbits
= ((nbits
+ 31) / 32) * 32;
3129 log_info(_("keysize rounded up to %u bits\n"), nbits
);
3132 dek
= do_ask_passphrase (&s2k
, &canceled
);
3135 rc
= gpg_error (GPG_ERR_CANCELED
);
3139 sk
= xmalloc_clear (sizeof *sk
);
3140 sk
->timestamp
= created_at
;
3142 sk
->pubkey_algo
= algo
;
3144 if ( !is_RSA (algo
) )
3146 log_error ("only RSA is supported for offline generated keys\n");
3147 rc
= gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
3150 rc
= gcry_sexp_build (&s_parms
, NULL
,
3151 "(genkey(rsa(nbits %d)))",
3154 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
3155 rc
= gcry_pk_genkey (&s_key
, s_parms
);
3156 gcry_sexp_release (s_parms
);
3159 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
3162 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
3163 gcry_sexp_release (s_key
);
3166 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
3170 for (i
=npkey
; i
< nskey
; i
++)
3171 sk
->csum
+= checksum_mpi (sk
->skey
[i
]);
3173 if (r_sk_unprotected
)
3174 *r_sk_unprotected
= copy_secret_key (NULL
, sk
);
3176 rc
= genhelp_protect (dek
, s2k
, sk
);
3182 *r_sk_protected
= sk
;
3188 free_secret_key (sk
);
3193 #endif /* ENABLE_CARD_SUPPORT */
3195 /* Create and delete a dummy packet to start off a list of kbnodes. */
3197 start_tree(KBNODE
*tree
)
3201 pkt
=xmalloc_clear(sizeof(*pkt
));
3202 pkt
->pkttype
=PKT_NONE
;
3203 *tree
=new_kbnode(pkt
);
3204 delete_kbnode(*tree
);
3209 do_generate_keypair (struct para_data_s
*para
,
3210 struct output_control_s
*outctrl
, int card
)
3212 KBNODE pub_root
= NULL
;
3213 KBNODE sec_root
= NULL
;
3214 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3216 struct revocation_key
*revkey
;
3221 if( outctrl
->dryrun
)
3223 log_info("dry-run mode - key generation skipped\n");
3227 if ( outctrl
->use_files
)
3229 if ( outctrl
->pub
.newfname
)
3231 iobuf_close(outctrl
->pub
.stream
);
3232 outctrl
->pub
.stream
= NULL
;
3233 if (outctrl
->pub
.fname
)
3234 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->pub
.fname
);
3235 xfree( outctrl
->pub
.fname
);
3236 outctrl
->pub
.fname
= outctrl
->pub
.newfname
;
3237 outctrl
->pub
.newfname
= NULL
;
3239 if (is_secured_filename (outctrl
->pub
.fname
) )
3241 outctrl
->pub
.stream
= NULL
;
3245 outctrl
->pub
.stream
= iobuf_create( outctrl
->pub
.fname
);
3246 if (!outctrl
->pub
.stream
)
3248 log_error(_("can't create `%s': %s\n"), outctrl
->pub
.newfname
,
3254 outctrl
->pub
.afx
->what
= 1;
3255 push_armor_filter (outctrl
->pub
.afx
, outctrl
->pub
.stream
);
3258 if (outctrl
->sec
.newfname
)
3262 iobuf_close(outctrl
->sec
.stream
);
3263 outctrl
->sec
.stream
= NULL
;
3264 if (outctrl
->sec
.fname
)
3265 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->sec
.fname
);
3266 xfree( outctrl
->sec
.fname
);
3267 outctrl
->sec
.fname
= outctrl
->sec
.newfname
;
3268 outctrl
->sec
.newfname
= NULL
;
3270 oldmask
= umask (077);
3271 if (is_secured_filename (outctrl
->sec
.fname
) )
3273 outctrl
->sec
.stream
= NULL
;
3277 outctrl
->sec
.stream
= iobuf_create( outctrl
->sec
.fname
);
3279 if (!outctrl
->sec
.stream
)
3281 log_error(_("can't create `%s': %s\n"), outctrl
->sec
.newfname
,
3287 outctrl
->sec
.afx
->what
= 5;
3288 push_armor_filter (outctrl
->sec
.afx
, outctrl
->sec
.stream
);
3291 assert( outctrl
->pub
.stream
);
3292 assert( outctrl
->sec
.stream
);
3295 log_info (_("writing public key to `%s'\n"), outctrl
->pub
.fname
);
3297 log_info (_("writing secret key stub to `%s'\n"),
3298 outctrl
->sec
.fname
);
3300 log_info(_("writing secret key to `%s'\n"), outctrl
->sec
.fname
);
3305 /* We create the packets as a tree of kbnodes. Because the
3306 structure we create is known in advance we simply generate a
3307 linked list. The first packet is a dummy packet which we flag as
3308 deleted. The very first packet must always be a KEY packet. */
3310 start_tree (&pub_root
);
3311 start_tree (&sec_root
);
3313 timestamp
= get_parameter_u32 (para
, pKEYCREATIONDATE
);
3315 timestamp
= make_timestamp ();
3319 rc
= do_create (get_parameter_algo( para
, pKEYTYPE
),
3320 get_parameter_uint( para
, pKEYLENGTH
),
3322 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3323 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3326 get_parameter_u32( para
, pKEYEXPIRE
), 0 );
3330 /* Note, that depending on the backend, the card key generation
3331 may update TIMESTAMP. */
3332 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 1, 1, pub_root
, sec_root
, NULL
,
3334 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3337 pri_sk
= sec_root
->next
->pkt
->pkt
.secret_key
;
3342 if(!rc
&& (revkey
=get_parameter_revkey(para
,pREVOKER
)))
3344 rc
= write_direct_sig (pub_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3346 rc
= write_direct_sig (sec_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3349 if( !rc
&& (s
=get_parameter_value(para
, pUSERID
)) )
3351 write_uid (pub_root
, s
);
3352 write_uid (sec_root
, s
);
3354 rc
= write_selfsigs (sec_root
, pub_root
, pri_sk
,
3355 get_parameter_uint (para
, pKEYUSAGE
), timestamp
);
3358 /* Write the auth key to the card before the encryption key. This
3359 is a partial workaround for a PGP bug (as of this writing, all
3360 versions including 8.1), that causes it to try and encrypt to
3361 the most recent subkey regardless of whether that subkey is
3362 actually an encryption type. In this case, the auth key is an
3363 RSA key so it succeeds. */
3365 if (!rc
&& card
&& get_parameter (para
, pAUTHKEYTYPE
))
3367 /* Note, that depending on the backend, the card key generation
3368 may update TIMESTAMP. */
3369 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 3, 0, pub_root
, sec_root
, NULL
,
3371 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3374 rc
= write_keybinding (pub_root
, pub_root
, pri_sk
, sub_sk
,
3375 PUBKEY_USAGE_AUTH
, timestamp
);
3377 rc
= write_keybinding (sec_root
, pub_root
, pri_sk
, sub_sk
,
3378 PUBKEY_USAGE_AUTH
, timestamp
);
3381 if( !rc
&& get_parameter( para
, pSUBKEYTYPE
) )
3385 rc
= do_create( get_parameter_algo( para
, pSUBKEYTYPE
),
3386 get_parameter_uint( para
, pSUBKEYLENGTH
),
3388 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3389 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3392 get_parameter_u32( para
, pSUBKEYEXPIRE
), 1 );
3396 if ((s
= get_parameter_value (para
, pBACKUPENCDIR
)))
3398 /* A backup of the encryption key has been requested.
3399 Generate the key in software and import it then to
3400 the card. Write a backup file. */
3401 rc
= gen_card_key_with_backup (PUBKEY_ALGO_RSA
, 2, 0,
3404 get_parameter_u32 (para
,
3410 /* Note, that depending on the backend, the card key
3411 generation may update TIMESTAMP. */
3412 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 2, 0, pub_root
, sec_root
,
3415 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3420 rc
= write_keybinding(pub_root
, pub_root
, pri_sk
, sub_sk
,
3421 get_parameter_uint (para
, pSUBKEYUSAGE
),
3424 rc
= write_keybinding(sec_root
, pub_root
, pri_sk
, sub_sk
,
3425 get_parameter_uint (para
, pSUBKEYUSAGE
),
3430 if (!rc
&& outctrl
->use_files
) /* Direct write to specified files. */
3432 rc
= write_keyblock( outctrl
->pub
.stream
, pub_root
);
3434 log_error ("can't write public key: %s\n", g10_errstr(rc
) );
3437 rc
= write_keyblock( outctrl
->sec
.stream
, sec_root
);
3439 log_error ("can't write secret key: %s\n", g10_errstr(rc
) );
3442 else if (!rc
) /* Write to the standard keyrings. */
3444 KEYDB_HANDLE pub_hd
= keydb_new (0);
3445 KEYDB_HANDLE sec_hd
= keydb_new (1);
3447 rc
= keydb_locate_writable (pub_hd
, NULL
);
3449 log_error (_("no writable public keyring found: %s\n"),
3454 rc
= keydb_locate_writable (sec_hd
, NULL
);
3456 log_error (_("no writable secret keyring found: %s\n"),
3460 if (!rc
&& opt
.verbose
)
3462 log_info (_("writing public key to `%s'\n"),
3463 keydb_get_resource_name (pub_hd
));
3465 log_info (_("writing secret key stub to `%s'\n"),
3466 keydb_get_resource_name (sec_hd
));
3468 log_info (_("writing secret key to `%s'\n"),
3469 keydb_get_resource_name (sec_hd
));
3474 rc
= keydb_insert_keyblock (pub_hd
, pub_root
);
3476 log_error (_("error writing public keyring `%s': %s\n"),
3477 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3482 rc
= keydb_insert_keyblock (sec_hd
, sec_root
);
3484 log_error (_("error writing secret keyring `%s': %s\n"),
3485 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3488 keydb_release (pub_hd
);
3489 keydb_release (sec_hd
);
3496 no_enc_rsa
= (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_RSA
3497 && get_parameter_uint (para
, pKEYUSAGE
)
3498 && !((get_parameter_uint (para
, pKEYUSAGE
)
3499 & PUBKEY_USAGE_ENC
)) );
3501 pk
= find_kbnode (pub_root
, PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3503 keyid_from_pk(pk
,pk
->main_keyid
);
3504 register_trusted_keyid(pk
->main_keyid
);
3506 update_ownertrust (pk
, ((get_ownertrust (pk
) & ~TRUST_MASK
)
3507 | TRUST_ULTIMATE
));
3511 tty_printf (_("public and secret key created and signed.\n") );
3513 list_keyblock(pub_root
,0,1,NULL
);
3518 && (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_DSA
3520 && !get_parameter (para
, pSUBKEYTYPE
) )
3522 tty_printf(_("Note that this key cannot be used for "
3523 "encryption. You may want to use\n"
3524 "the command \"--edit-key\" to generate a "
3525 "subkey for this purpose.\n") );
3533 log_error ("key generation failed: %s\n", g10_errstr(rc
) );
3535 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3536 print_status_key_not_created ( get_parameter_value (para
, pHANDLE
) );
3540 PKT_public_key
*pk
= find_kbnode (pub_root
,
3541 PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3542 print_status_key_created (did_sub
? 'B':'P', pk
,
3543 get_parameter_value (para
, pHANDLE
));
3545 release_kbnode( pub_root
);
3546 release_kbnode( sec_root
);
3548 if (pri_sk
&& !card
) /* The unprotected secret key unless we */
3549 free_secret_key (pri_sk
); /* have a shallow copy in card mode. */
3551 free_secret_key(sub_sk
);
3555 /* Add a new subkey to an existing key. Returns true if a new key has
3556 been generated and put into the keyblocks. */
3558 generate_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
)
3562 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3567 char *passphrase
= NULL
;
3569 STRING2KEY
*s2k
= NULL
;
3574 /* Break out the primary secret key. */
3575 node
= find_kbnode( sec_keyblock
, PKT_SECRET_KEY
);
3578 log_error ("Oops; secret key not found anymore!\n");
3582 /* Make a copy of the sk to keep the protected one in the keyblock. */
3583 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3585 cur_time
= make_timestamp();
3587 if (pri_sk
->timestamp
> cur_time
)
3589 ulong d
= pri_sk
->timestamp
- cur_time
;
3590 log_info ( d
==1 ? _("key has been created %lu second "
3591 "in future (time warp or clock problem)\n")
3592 : _("key has been created %lu seconds "
3593 "in future (time warp or clock problem)\n"), d
);
3594 if (!opt
.ignore_time_conflict
)
3596 rc
= G10ERR_TIME_CONFLICT
;
3601 if (pri_sk
->version
< 4)
3603 log_info (_("NOTE: creating subkeys for v3 keys "
3604 "is not OpenPGP compliant\n"));
3608 if (pri_sk
->is_protected
&& pri_sk
->protect
.s2k
.mode
== 1001)
3610 tty_printf (_("Secret parts of primary key are not available.\n"));
3611 rc
= G10ERR_NO_SECKEY
;
3616 /* Unprotect to get the passphrase. */
3617 switch (is_secret_key_protected (pri_sk
) )
3620 rc
= G10ERR_PUBKEY_ALGO
;
3623 tty_printf (_("This key is not protected.\n"));
3626 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3630 tty_printf (_("Key is protected.\n"));
3631 rc
= check_secret_key ( pri_sk
, 0 );
3633 passphrase
= get_last_passphrase();
3639 algo
= ask_algo (1, &use
);
3641 nbits
= ask_keysize (algo
);
3642 expire
= ask_expire_interval (0, NULL
);
3643 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3644 _("Really create? (y/N) ")))
3649 dek
= do_ask_passphrase (&s2k
, &canceled
);
3650 else if (passphrase
)
3652 s2k
= xmalloc_secure ( sizeof *s2k
);
3653 s2k
->mode
= opt
.s2k_mode
;
3654 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
3655 set_next_passphrase ( passphrase
);
3656 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
3661 rc
= GPG_ERR_CANCELED
;
3664 rc
= do_create (algo
, nbits
, pub_keyblock
, sec_keyblock
,
3665 dek
, s2k
, &sub_sk
, cur_time
, expire
, 1 );
3667 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3670 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3675 write_status_text (STATUS_KEY_CREATED
, "S");
3680 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3684 /* Release the copy of the (now unprotected) secret keys. */
3686 free_secret_key (pri_sk
);
3688 free_secret_key (sub_sk
);
3689 set_next_passphrase (NULL
);
3694 #ifdef ENABLE_CARD_SUPPORT
3695 /* Generate a subkey on a card. */
3697 generate_card_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
,
3698 int keyno
, const char *serialno
)
3702 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
;
3706 char *passphrase
= NULL
;
3708 struct para_data_s
*para
= NULL
;
3710 assert (keyno
>= 1 && keyno
<= 3);
3712 para
= xcalloc (1, sizeof *para
+ strlen (serialno
) );
3713 para
->key
= pSERIALNO
;
3714 strcpy (para
->u
.value
, serialno
);
3716 /* Break out the primary secret key */
3717 node
= find_kbnode (sec_keyblock
, PKT_SECRET_KEY
);
3720 log_error("Oops; secret key not found anymore!\n");
3724 /* Make a copy of the sk to keep the protected one in the keyblock */
3725 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3727 cur_time
= make_timestamp();
3728 if (pri_sk
->timestamp
> cur_time
)
3730 ulong d
= pri_sk
->timestamp
- cur_time
;
3731 log_info (d
==1 ? _("key has been created %lu second "
3732 "in future (time warp or clock problem)\n")
3733 : _("key has been created %lu seconds "
3734 "in future (time warp or clock problem)\n"), d
);
3735 if (!opt
.ignore_time_conflict
)
3737 rc
= G10ERR_TIME_CONFLICT
;
3742 if (pri_sk
->version
< 4)
3744 log_info (_("NOTE: creating subkeys for v3 keys "
3745 "is not OpenPGP compliant\n"));
3749 /* Unprotect to get the passphrase. */
3750 switch( is_secret_key_protected (pri_sk
) )
3753 rc
= G10ERR_PUBKEY_ALGO
;
3756 tty_printf("This key is not protected.\n");
3759 tty_printf("Key is protected.\n");
3760 rc
= check_secret_key( pri_sk
, 0 );
3762 passphrase
= get_last_passphrase();
3768 algo
= PUBKEY_ALGO_RSA
;
3769 expire
= ask_expire_interval (0,NULL
);
3771 use
= PUBKEY_USAGE_SIG
;
3772 else if (keyno
== 2)
3773 use
= PUBKEY_USAGE_ENC
;
3775 use
= PUBKEY_USAGE_AUTH
;
3776 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3777 _("Really create? (y/N) ")))
3781 set_next_passphrase (passphrase
);
3783 /* Note, that depending on the backend, the card key generation may
3785 rc
= gen_card_key (algo
, keyno
, 0, pub_keyblock
, sec_keyblock
,
3786 &sub_sk
, &cur_time
, expire
, para
);
3788 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3791 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3796 write_status_text (STATUS_KEY_CREATED
, "S");
3801 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3803 /* Release the copy of the (now unprotected) secret keys. */
3805 free_secret_key (pri_sk
);
3806 set_next_passphrase( NULL
);
3807 release_parameter_list (para
);
3810 #endif /* !ENABLE_CARD_SUPPORT */
3814 * Write a keyblock to an output stream
3817 write_keyblock( IOBUF out
, KBNODE node
)
3819 for( ; node
; node
= node
->next
)
3821 if(!is_deleted_kbnode(node
))
3823 int rc
= build_packet( out
, node
->pkt
);
3826 log_error("build_packet(%d) failed: %s\n",
3827 node
->pkt
->pkttype
, g10_errstr(rc
) );
3837 /* Note that timestamp is an in/out arg. */
3839 gen_card_key (int algo
, int keyno
, int is_primary
,
3840 KBNODE pub_root
, KBNODE sec_root
, PKT_secret_key
**ret_sk
,
3841 u32
*timestamp
, u32 expireval
, struct para_data_s
*para
)
3843 #ifdef ENABLE_CARD_SUPPORT
3846 struct agent_card_genkey_s info
;
3851 assert (algo
== PUBKEY_ALGO_RSA
);
3853 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3854 rc
= agent_scd_genkey (&info
, keyno
, 1, NULL
, *timestamp
);
3855 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3857 /* tty_printf ("\n"); */
3858 /* log_error ("WARNING: key does already exists!\n"); */
3859 /* tty_printf ("\n"); */
3860 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3861 /* _("Replace existing key? "))) */
3862 /* rc = agent_scd_genkey (&info, keyno, 1); */
3867 log_error ("key generation failed: %s\n", gpg_strerror (rc
));
3870 if ( !info
.n
|| !info
.e
)
3872 log_error ("communication error with SCD\n");
3873 gcry_mpi_release (info
.n
);
3874 gcry_mpi_release (info
.e
);
3875 return gpg_error (GPG_ERR_GENERAL
);
3878 if (*timestamp
!= info
.created_at
)
3879 log_info ("Note that the key does not use the suggested creation date\n");
3880 *timestamp
= info
.created_at
;
3882 pk
= xcalloc (1, sizeof *pk
);
3883 sk
= xcalloc (1, sizeof *sk
);
3884 sk
->timestamp
= pk
->timestamp
= info
.created_at
;
3885 sk
->version
= pk
->version
= 4;
3887 sk
->expiredate
= pk
->expiredate
= pk
->timestamp
+ expireval
;
3888 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
3889 pk
->pkey
[0] = info
.n
;
3890 pk
->pkey
[1] = info
.e
;
3891 sk
->skey
[0] = gcry_mpi_copy (pk
->pkey
[0]);
3892 sk
->skey
[1] = gcry_mpi_copy (pk
->pkey
[1]);
3893 sk
->skey
[2] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3894 sk
->is_protected
= 1;
3895 sk
->protect
.s2k
.mode
= 1002;
3896 s
= get_parameter_value (para
, pSERIALNO
);
3899 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
3900 sk
->protect
.ivlen
++, s
+= 2)
3901 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
3907 pkt
= xcalloc (1,sizeof *pkt
);
3908 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
3909 pkt
->pkt
.public_key
= pk
;
3910 add_kbnode(pub_root
, new_kbnode( pkt
));
3912 pkt
= xcalloc (1,sizeof *pkt
);
3913 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
3914 pkt
->pkt
.secret_key
= sk
;
3915 add_kbnode(sec_root
, new_kbnode( pkt
));
3920 #endif /*!ENABLE_CARD_SUPPORT*/
3926 gen_card_key_with_backup (int algo
, int keyno
, int is_primary
,
3927 KBNODE pub_root
, KBNODE sec_root
,
3929 u32 expireval
, struct para_data_s
*para
,
3930 const char *backup_dir
)
3932 #ifdef ENABLE_CARD_SUPPORT
3936 PKT_secret_key
*sk
, *sk_unprotected
= NULL
, *sk_protected
= NULL
;
3941 rc
= generate_raw_key (algo
, 1024, timestamp
,
3942 &sk_unprotected
, &sk_protected
);
3946 /* First, store the key to the card. */
3947 rc
= save_unprotected_key_to_card (sk_unprotected
, keyno
);
3950 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc
));
3951 free_secret_key (sk_unprotected
);
3952 free_secret_key (sk_protected
);
3956 /* Get rid of the secret key parameters and store the serial numer. */
3957 sk
= sk_unprotected
;
3958 n
= pubkey_get_nskey (sk
->pubkey_algo
);
3959 for (i
=pubkey_get_npkey (sk
->pubkey_algo
); i
< n
; i
++)
3961 gcry_mpi_release (sk
->skey
[i
]);
3964 i
= pubkey_get_npkey (sk
->pubkey_algo
);
3965 sk
->skey
[i
] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3966 sk
->is_protected
= 1;
3967 sk
->protect
.s2k
.mode
= 1002;
3968 s
= get_parameter_value (para
, pSERIALNO
);
3970 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
3971 sk
->protect
.ivlen
++, s
+= 2)
3972 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
3974 /* Now write the *protected* secret key to the file. */
3976 char name_buffer
[50];
3981 keyid_from_sk (sk
, NULL
);
3982 sprintf (name_buffer
,"sk_%08lX%08lX.gpg",
3983 (ulong
)sk
->keyid
[0], (ulong
)sk
->keyid
[1]);
3985 fname
= make_filename (backup_dir
, name_buffer
, NULL
);
3986 oldmask
= umask (077);
3987 if (is_secured_filename (fname
))
3993 fp
= iobuf_create (fname
);
3997 rc
= gpg_error_from_syserror ();
3998 log_error (_("can't create backup file `%s': %s\n"),
3999 fname
, strerror(errno
) );
4001 free_secret_key (sk_unprotected
);
4002 free_secret_key (sk_protected
);
4006 pkt
= xcalloc (1, sizeof *pkt
);
4007 pkt
->pkttype
= PKT_SECRET_KEY
;
4008 pkt
->pkt
.secret_key
= sk_protected
;
4009 sk_protected
= NULL
;
4011 rc
= build_packet (fp
, pkt
);
4014 log_error("build packet failed: %s\n", g10_errstr(rc
) );
4019 unsigned char array
[MAX_FINGERPRINT_LEN
];
4023 iobuf_ioctl (NULL
, 2, 0, (char*)fname
);
4024 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname
);
4026 fingerprint_from_sk (sk
, array
, &n
);
4027 p
= fprbuf
= xmalloc (MAX_FINGERPRINT_LEN
*2 + 1 + 1);
4028 for (i
=0; i
< n
; i
++, p
+= 2)
4029 sprintf (p
, "%02X", array
[i
]);
4033 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED
,
4035 fname
, strlen (fname
),
4044 free_secret_key (sk_unprotected
);
4049 /* Create the public key from the secret key. */
4050 pk
= xcalloc (1, sizeof *pk
);
4051 pk
->timestamp
= sk
->timestamp
;
4052 pk
->version
= sk
->version
;
4054 pk
->expiredate
= sk
->expiredate
= sk
->timestamp
+ expireval
;
4055 pk
->pubkey_algo
= sk
->pubkey_algo
;
4056 n
= pubkey_get_npkey (sk
->pubkey_algo
);
4057 for (i
=0; i
< n
; i
++)
4058 pk
->pkey
[i
] = mpi_copy (sk
->skey
[i
]);
4060 /* Build packets and add them to the node lists. */
4061 pkt
= xcalloc (1,sizeof *pkt
);
4062 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
4063 pkt
->pkt
.public_key
= pk
;
4064 add_kbnode(pub_root
, new_kbnode( pkt
));
4066 pkt
= xcalloc (1,sizeof *pkt
);
4067 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
4068 pkt
->pkt
.secret_key
= sk
;
4069 add_kbnode(sec_root
, new_kbnode( pkt
));
4074 #endif /*!ENABLE_CARD_SUPPORT*/
4078 #ifdef ENABLE_CARD_SUPPORT
4080 save_unprotected_key_to_card (PKT_secret_key
*sk
, int keyno
)
4083 unsigned char *rsa_n
= NULL
;
4084 unsigned char *rsa_e
= NULL
;
4085 unsigned char *rsa_p
= NULL
;
4086 unsigned char *rsa_q
= NULL
;
4087 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
4088 unsigned char *sexp
= NULL
;
4090 char numbuf
[55], numbuf2
[50];
4092 assert (is_RSA (sk
->pubkey_algo
));
4093 assert (!sk
->is_protected
);
4095 /* Copy the parameters into straight buffers. */
4096 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_n
, &rsa_n_len
, sk
->skey
[0]);
4097 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_e
, &rsa_e_len
, sk
->skey
[1]);
4098 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_p
, &rsa_p_len
, sk
->skey
[3]);
4099 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_q
, &rsa_q_len
, sk
->skey
[4]);
4100 if (!rsa_n
|| !rsa_e
|| !rsa_p
|| !rsa_q
)
4102 rc
= G10ERR_INV_ARG
;
4106 /* Put the key into an S-expression. */
4107 sexp
= p
= xmalloc_secure (30
4108 + rsa_n_len
+ rsa_e_len
+ rsa_p_len
+ rsa_q_len
4109 + 4*sizeof (numbuf
) + 25 + sizeof(numbuf
) + 20);
4111 p
= stpcpy (p
,"(11:private-key(3:rsa(1:n");
4112 sprintf (numbuf
, "%u:", (unsigned int)rsa_n_len
);
4113 p
= stpcpy (p
, numbuf
);
4114 memcpy (p
, rsa_n
, rsa_n_len
);
4117 sprintf (numbuf
, ")(1:e%u:", (unsigned int)rsa_e_len
);
4118 p
= stpcpy (p
, numbuf
);
4119 memcpy (p
, rsa_e
, rsa_e_len
);
4122 sprintf (numbuf
, ")(1:p%u:", (unsigned int)rsa_p_len
);
4123 p
= stpcpy (p
, numbuf
);
4124 memcpy (p
, rsa_p
, rsa_p_len
);
4127 sprintf (numbuf
, ")(1:q%u:", (unsigned int)rsa_q_len
);
4128 p
= stpcpy (p
, numbuf
);
4129 memcpy (p
, rsa_q
, rsa_q_len
);
4132 p
= stpcpy (p
,"))(10:created-at");
4133 sprintf (numbuf2
, "%lu", (unsigned long)sk
->timestamp
);
4134 sprintf (numbuf
, "%lu:", (unsigned long)strlen (numbuf2
));
4135 p
= stpcpy (stpcpy (stpcpy (p
, numbuf
), numbuf2
), "))");
4137 /* Fixme: Unfortunately we don't have the serialnumber available -
4138 thus we can't pass it down to the agent. */
4139 rc
= agent_scd_writekey (keyno
, NULL
, sexp
, p
- sexp
);
4149 #endif /*ENABLE_CARD_SUPPORT*/