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 if (!openpgp_md_test_algo(DIGEST_ALGO_RMD160
))
356 strcat(dummy_string
,"H3 ");
359 strcat(dummy_string
,"Z2 ");
361 if(!check_compress_algo(COMPRESS_ALGO_BZIP2
))
362 strcat(dummy_string
,"Z3 ");
365 strcat(dummy_string
,"Z1");
370 else if (!ascii_strcasecmp (string
, "none"))
375 char *tok
,*prefstring
;
377 prefstring
=xstrdup(string
); /* need a writable string! */
379 while((tok
=strsep(&prefstring
," ,")))
381 if((val
=string_to_cipher_algo (tok
)))
383 if(set_one_pref(val
,1,tok
,sym
,&nsym
))
386 else if((val
=string_to_digest_algo (tok
)))
388 if(set_one_pref(val
,2,tok
,hash
,&nhash
))
391 else if((val
=string_to_compress_algo(tok
))>-1)
393 if(set_one_pref(val
,3,tok
,zip
,&nzip
))
396 else if (ascii_strcasecmp(tok
,"mdc")==0)
398 else if (ascii_strcasecmp(tok
,"no-mdc")==0)
400 else if (ascii_strcasecmp(tok
,"ks-modify")==0)
402 else if (ascii_strcasecmp(tok
,"no-ks-modify")==0)
406 log_info (_("invalid item `%s' in preference string\n"),tok
);
408 /* Complain if IDEA is not available. */
409 if(ascii_strcasecmp(tok
,"s1")==0
410 || ascii_strcasecmp(tok
,"idea")==0)
424 if(personal
==PREFTYPE_SYM
)
426 xfree(opt
.personal_cipher_prefs
);
429 opt
.personal_cipher_prefs
=NULL
;
434 opt
.personal_cipher_prefs
=
435 xmalloc(sizeof(prefitem_t
*)*(nsym
+1));
437 for (i
=0; i
<nsym
; i
++)
439 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_SYM
;
440 opt
.personal_cipher_prefs
[i
].value
= sym
[i
];
443 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_NONE
;
444 opt
.personal_cipher_prefs
[i
].value
= 0;
447 else if(personal
==PREFTYPE_HASH
)
449 xfree(opt
.personal_digest_prefs
);
452 opt
.personal_digest_prefs
=NULL
;
457 opt
.personal_digest_prefs
=
458 xmalloc(sizeof(prefitem_t
*)*(nhash
+1));
460 for (i
=0; i
<nhash
; i
++)
462 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_HASH
;
463 opt
.personal_digest_prefs
[i
].value
= hash
[i
];
466 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_NONE
;
467 opt
.personal_digest_prefs
[i
].value
= 0;
470 else if(personal
==PREFTYPE_ZIP
)
472 xfree(opt
.personal_compress_prefs
);
475 opt
.personal_compress_prefs
=NULL
;
480 opt
.personal_compress_prefs
=
481 xmalloc(sizeof(prefitem_t
*)*(nzip
+1));
483 for (i
=0; i
<nzip
; i
++)
485 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_ZIP
;
486 opt
.personal_compress_prefs
[i
].value
= zip
[i
];
489 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_NONE
;
490 opt
.personal_compress_prefs
[i
].value
= 0;
496 memcpy (sym_prefs
, sym
, (nsym_prefs
=nsym
));
497 memcpy (hash_prefs
, hash
, (nhash_prefs
=nhash
));
498 memcpy (zip_prefs
, zip
, (nzip_prefs
=nzip
));
501 prefs_initialized
= 1;
508 /* Return a fake user ID containing the preferences. Caller must
510 PKT_user_id
*keygen_get_std_prefs(void)
513 PKT_user_id
*uid
=xmalloc_clear(sizeof(PKT_user_id
));
515 if(!prefs_initialized
)
516 keygen_set_std_prefs(NULL
,0);
520 uid
->prefs
=xmalloc((sizeof(prefitem_t
*)*
521 (nsym_prefs
+nhash_prefs
+nzip_prefs
+1)));
523 for(i
=0;i
<nsym_prefs
;i
++,j
++)
525 uid
->prefs
[j
].type
=PREFTYPE_SYM
;
526 uid
->prefs
[j
].value
=sym_prefs
[i
];
529 for(i
=0;i
<nhash_prefs
;i
++,j
++)
531 uid
->prefs
[j
].type
=PREFTYPE_HASH
;
532 uid
->prefs
[j
].value
=hash_prefs
[i
];
535 for(i
=0;i
<nzip_prefs
;i
++,j
++)
537 uid
->prefs
[j
].type
=PREFTYPE_ZIP
;
538 uid
->prefs
[j
].value
=zip_prefs
[i
];
541 uid
->prefs
[j
].type
=PREFTYPE_NONE
;
542 uid
->prefs
[j
].value
=0;
544 uid
->flags
.mdc
=mdc_available
;
545 uid
->flags
.ks_modify
=ks_modify
;
551 add_feature_mdc (PKT_signature
*sig
,int enabled
)
558 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
, &n
);
559 /* Already set or cleared */
561 ((enabled
&& (s
[0] & 0x01)) || (!enabled
&& !(s
[0] & 0x01))))
564 if (!s
|| !n
) { /* create a new one */
566 buf
= xmalloc_clear (n
);
574 buf
[0] |= 0x01; /* MDC feature */
578 /* Are there any bits set? */
584 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
);
586 build_sig_subpkt (sig
, SIGSUBPKT_FEATURES
, buf
, n
);
592 add_keyserver_modify (PKT_signature
*sig
,int enabled
)
599 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
602 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
, &n
);
603 /* Already set or cleared */
605 ((enabled
&& (s
[0] & 0x80)) || (!enabled
&& !(s
[0] & 0x80))))
608 if (!s
|| !n
) { /* create a new one */
610 buf
= xmalloc_clear (n
);
618 buf
[0] |= 0x80; /* no-modify flag */
622 /* Are there any bits set? */
628 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
);
630 build_sig_subpkt (sig
, SIGSUBPKT_KS_FLAGS
, buf
, n
);
637 keygen_upd_std_prefs (PKT_signature
*sig
, void *opaque
)
641 if (!prefs_initialized
)
642 keygen_set_std_prefs (NULL
, 0);
645 build_sig_subpkt (sig
, SIGSUBPKT_PREF_SYM
, sym_prefs
, nsym_prefs
);
648 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_SYM
);
649 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_SYM
);
653 build_sig_subpkt (sig
, SIGSUBPKT_PREF_HASH
, hash_prefs
, nhash_prefs
);
656 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_HASH
);
657 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_HASH
);
661 build_sig_subpkt (sig
, SIGSUBPKT_PREF_COMPR
, zip_prefs
, nzip_prefs
);
664 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_COMPR
);
665 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_COMPR
);
668 /* Make sure that the MDC feature flag is set if needed. */
669 add_feature_mdc (sig
,mdc_available
);
670 add_keyserver_modify (sig
,ks_modify
);
671 keygen_add_keyserver_url(sig
,NULL
);
678 * Add preference to the self signature packet.
679 * This is only called for packets with version > 3.
683 keygen_add_std_prefs( PKT_signature
*sig
, void *opaque
)
685 PKT_public_key
*pk
= opaque
;
687 do_add_key_flags (sig
, pk
->pubkey_usage
);
688 keygen_add_key_expire( sig
, opaque
);
689 keygen_upd_std_prefs (sig
, opaque
);
690 keygen_add_keyserver_url(sig
,NULL
);
696 keygen_add_keyserver_url(PKT_signature
*sig
, void *opaque
)
698 const char *url
=opaque
;
701 url
=opt
.def_keyserver_url
;
704 build_sig_subpkt(sig
,SIGSUBPKT_PREF_KS
,url
,strlen(url
));
706 delete_sig_subpkt (sig
->hashed
,SIGSUBPKT_PREF_KS
);
712 keygen_add_notations(PKT_signature
*sig
,void *opaque
)
714 struct notation
*notation
;
716 /* We always start clean */
717 delete_sig_subpkt(sig
->hashed
,SIGSUBPKT_NOTATION
);
718 delete_sig_subpkt(sig
->unhashed
,SIGSUBPKT_NOTATION
);
719 sig
->flags
.notation
=0;
721 for(notation
=opaque
;notation
;notation
=notation
->next
)
722 if(!notation
->flags
.ignore
)
727 n1
=strlen(notation
->name
);
728 if(notation
->altvalue
)
729 n2
=strlen(notation
->altvalue
);
730 else if(notation
->bdat
)
733 n2
=strlen(notation
->value
);
735 buf
= xmalloc( 8 + n1
+ n2
);
737 /* human readable or not */
738 buf
[0] = notation
->bdat
?0:0x80;
739 buf
[1] = buf
[2] = buf
[3] = 0;
744 memcpy(buf
+8, notation
->name
, n1
);
745 if(notation
->altvalue
)
746 memcpy(buf
+8+n1
, notation
->altvalue
, n2
);
747 else if(notation
->bdat
)
748 memcpy(buf
+8+n1
, notation
->bdat
, n2
);
750 memcpy(buf
+8+n1
, notation
->value
, n2
);
751 build_sig_subpkt( sig
, SIGSUBPKT_NOTATION
|
752 (notation
->flags
.critical
?SIGSUBPKT_FLAG_CRITICAL
:0),
761 keygen_add_revkey(PKT_signature
*sig
, void *opaque
)
763 struct revocation_key
*revkey
=opaque
;
764 byte buf
[2+MAX_FINGERPRINT_LEN
];
766 buf
[0]=revkey
->class;
767 buf
[1]=revkey
->algid
;
768 memcpy(&buf
[2],revkey
->fpr
,MAX_FINGERPRINT_LEN
);
770 build_sig_subpkt(sig
,SIGSUBPKT_REV_KEY
,buf
,2+MAX_FINGERPRINT_LEN
);
772 /* All sigs with revocation keys set are nonrevocable */
773 sig
->flags
.revocable
=0;
775 build_sig_subpkt( sig
, SIGSUBPKT_REVOCABLE
, buf
, 1 );
784 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
785 signature creation time. */
787 make_backsig (PKT_signature
*sig
,PKT_public_key
*pk
,
788 PKT_public_key
*sub_pk
,PKT_secret_key
*sub_sk
,
791 PKT_signature
*backsig
;
794 cache_public_key(sub_pk
);
796 rc
= make_keysig_packet (&backsig
, pk
, NULL
, sub_pk
, sub_sk
, 0x19,
797 0, 0, timestamp
, 0, NULL
, NULL
);
799 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc
));
802 /* Get it into a binary packed form. */
803 IOBUF backsig_out
=iobuf_temp();
806 init_packet(&backsig_pkt
);
807 backsig_pkt
.pkttype
=PKT_SIGNATURE
;
808 backsig_pkt
.pkt
.signature
=backsig
;
809 rc
=build_packet(backsig_out
,&backsig_pkt
);
810 free_packet(&backsig_pkt
);
812 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc
));
816 byte
*buf
=iobuf_get_temp_buffer(backsig_out
);
818 /* Remove the packet header */
828 pktlen
=(buf
[1]-192)*256;
834 pktlen
=buf
[2] << 24;
835 pktlen
|=buf
[3] << 16;
854 pktlen
=buf
[mark
++] << 24;
855 pktlen
|=buf
[mark
++] << 16;
858 pktlen
|=buf
[mark
++] << 8;
867 /* Now make the binary blob into a subpacket. */
868 build_sig_subpkt(sig
,SIGSUBPKT_SIGNATURE
,buf
,pktlen
);
870 iobuf_close(backsig_out
);
879 write_direct_sig (KBNODE root
, KBNODE pub_root
, PKT_secret_key
*sk
,
880 struct revocation_key
*revkey
, u32 timestamp
)
889 log_info(_("writing direct signature\n"));
891 /* Get the pk packet from the pub_tree. */
892 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
895 pk
= node
->pkt
->pkt
.public_key
;
897 /* We have to cache the key, so that the verification of the
898 signature creation is able to retrieve the public key. */
899 cache_public_key (pk
);
901 /* Make the signature. */
902 rc
= make_keysig_packet (&sig
,pk
,NULL
,NULL
,sk
,0x1F,
904 keygen_add_revkey
, revkey
);
907 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
911 pkt
= xmalloc_clear( sizeof *pkt
);
912 pkt
->pkttype
= PKT_SIGNATURE
;
913 pkt
->pkt
.signature
= sig
;
914 add_kbnode( root
, new_kbnode( pkt
) );
920 write_selfsigs( KBNODE sec_root
, KBNODE pub_root
, PKT_secret_key
*sk
,
921 unsigned int use
, u32 timestamp
)
931 log_info(_("writing self signature\n"));
933 /* Get the uid packet from the list. */
934 node
= find_kbnode( pub_root
, PKT_USER_ID
);
936 BUG(); /* No user id packet in tree. */
937 uid
= node
->pkt
->pkt
.user_id
;
939 /* Get the pk packet from the pub_tree. */
940 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
943 pk
= node
->pkt
->pkt
.public_key
;
944 pk
->pubkey_usage
= use
;
946 /* We have to cache the key, so that the verification of the
947 signature creation is able to retrieve the public key. */
948 cache_public_key (pk
);
950 /* Make the signature. */
951 rc
= make_keysig_packet (&sig
, pk
, uid
, NULL
, sk
, 0x13,
953 keygen_add_std_prefs
, pk
);
956 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
960 pkt
= xmalloc_clear( sizeof *pkt
);
961 pkt
->pkttype
= PKT_SIGNATURE
;
962 pkt
->pkt
.signature
= sig
;
963 add_kbnode( sec_root
, new_kbnode( pkt
) );
965 pkt
= xmalloc_clear( sizeof *pkt
);
966 pkt
->pkttype
= PKT_SIGNATURE
;
967 pkt
->pkt
.signature
= copy_signature(NULL
,sig
);
968 add_kbnode( pub_root
, new_kbnode( pkt
) );
973 /* Write the key binding signature. If TIMESTAMP is not NULL use the
974 signature creation times. */
976 write_keybinding (KBNODE root
, KBNODE pub_root
,
977 PKT_secret_key
*pri_sk
, PKT_secret_key
*sub_sk
,
978 unsigned int use
, u32 timestamp
)
984 PKT_public_key
*pri_pk
, *sub_pk
;
985 struct opaque_data_usage_and_pk oduap
;
988 log_info(_("writing key binding signature\n"));
990 /* Get the pk packet from the pub_tree. */
991 node
= find_kbnode ( pub_root
, PKT_PUBLIC_KEY
);
994 pri_pk
= node
->pkt
->pkt
.public_key
;
996 /* We have to cache the key, so that the verification of the
997 * signature creation is able to retrieve the public key. */
998 cache_public_key (pri_pk
);
1000 /* Find the last subkey. */
1002 for (node
=pub_root
; node
; node
= node
->next
)
1004 if ( node
->pkt
->pkttype
== PKT_PUBLIC_SUBKEY
)
1005 sub_pk
= node
->pkt
->pkt
.public_key
;
1010 /* Make the signature. */
1013 rc
= make_keysig_packet (&sig
, pri_pk
, NULL
, sub_pk
, pri_sk
, 0x18,
1015 keygen_add_key_flags_and_expire
, &oduap
);
1018 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
1022 /* Make a backsig. */
1023 if (use
&PUBKEY_USAGE_SIG
)
1025 rc
= make_backsig (sig
, pri_pk
, sub_pk
, sub_sk
, timestamp
);
1030 pkt
= xmalloc_clear ( sizeof *pkt
);
1031 pkt
->pkttype
= PKT_SIGNATURE
;
1032 pkt
->pkt
.signature
= sig
;
1033 add_kbnode (root
, new_kbnode (pkt
) );
1040 key_from_sexp (gcry_mpi_t
*array
, gcry_sexp_t sexp
,
1041 const char *topname
, const char *elems
)
1043 gcry_sexp_t list
, l2
;
1048 list
= gcry_sexp_find_token (sexp
, topname
, 0);
1050 return gpg_error (GPG_ERR_INV_OBJ
);
1051 l2
= gcry_sexp_cadr (list
);
1052 gcry_sexp_release (list
);
1055 return gpg_error (GPG_ERR_NO_OBJ
);
1057 for (idx
=0,s
=elems
; *s
; s
++, idx
++)
1059 l2
= gcry_sexp_find_token (list
, s
, 1);
1062 rc
= gpg_error (GPG_ERR_NO_OBJ
); /* required parameter not found */
1065 array
[idx
] = gcry_sexp_nth_mpi (l2
, 1, GCRYMPI_FMT_USG
);
1066 gcry_sexp_release (l2
);
1069 rc
= gpg_error (GPG_ERR_INV_OBJ
); /* required parameter invalid */
1073 gcry_sexp_release (list
);
1078 for (i
=0; i
<idx
; i
++)
1083 gcry_sexp_release (list
);
1090 genhelp_protect (DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
*sk
)
1096 sk
->protect
.algo
= dek
->algo
;
1097 sk
->protect
.s2k
= *s2k
;
1098 rc
= protect_secret_key (sk
, dek
);
1100 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc
) );
1107 genhelp_factors (gcry_sexp_t misc_key_info
, KBNODE sec_root
)
1109 (void)misc_key_info
;
1111 #if 0 /* Not used anymore */
1117 /* DSA: don't know whether it makes sense to have the factors, so for now
1118 we store them in the secret keyring (but they are not secret)
1119 p = 2 * q * f1 * f2 * ... * fn
1120 We store only f1 to f_n-1; fn can be calculated because p and q
1122 n
= gcry_sexp_sprint (misc_key_info
, 0, NULL
, 0);
1123 buf
= xmalloc (n
+4);
1124 strcpy (buf
, "#::");
1125 n
= gcry_sexp_sprint (misc_key_info
, 0, buf
+3, n
);
1129 add_kbnode (sec_root
, make_comment_node_from_buffer (buf
, n
));
1132 gcry_sexp_release (misc_key_info
);
1138 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1139 time to be put into the key structure. */
1141 gen_elg (int algo
, unsigned int nbits
,
1142 KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1143 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1144 u32 timestamp
, u32 expireval
, int is_subkey
)
1150 gcry_sexp_t s_parms
, s_key
;
1151 gcry_sexp_t misc_key_info
;
1153 assert( is_ELGAMAL(algo
) );
1158 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1163 nbits
= ((nbits
+ 31) / 32) * 32;
1164 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1168 rc
= gcry_sexp_build ( &s_parms
, NULL
,
1169 "(genkey(%s(nbits %d)))",
1170 algo
== GCRY_PK_ELG_E
? "openpgp-elg" :
1171 algo
== GCRY_PK_ELG
? "elg" : "x-oops" ,
1174 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1176 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1177 gcry_sexp_release (s_parms
);
1180 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1184 sk
= xmalloc_clear( sizeof *sk
);
1185 pk
= xmalloc_clear( sizeof *pk
);
1186 sk
->timestamp
= pk
->timestamp
= timestamp
;
1187 sk
->version
= pk
->version
= 4;
1190 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1192 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1194 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pgy");
1197 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1198 gcry_sexp_release (s_key
);
1199 free_secret_key (sk
);
1200 free_public_key (pk
);
1203 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pgyx");
1206 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1207 gcry_sexp_release (s_key
);
1208 free_secret_key (sk
);
1209 free_public_key (pk
);
1212 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1213 gcry_sexp_release (s_key
);
1215 sk
->is_protected
= 0;
1216 sk
->protect
.algo
= 0;
1218 sk
->csum
= checksum_mpi (sk
->skey
[3]);
1219 if (ret_sk
) /* Return an unprotected version of the sk. */
1220 *ret_sk
= copy_secret_key ( NULL
, sk
);
1222 rc
= genhelp_protect (dek
, s2k
, sk
);
1225 free_public_key (pk
);
1226 free_secret_key (sk
);
1227 gcry_sexp_release (misc_key_info
);
1231 pkt
= xmalloc_clear (sizeof *pkt
);
1232 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1233 pkt
->pkt
.public_key
= pk
;
1234 add_kbnode (pub_root
, new_kbnode( pkt
));
1236 /* Don't know whether it makes sense to have access to the factors,
1237 so for now we store them in the secret keyring (but they are not
1239 pkt
= xmalloc_clear (sizeof *pkt
);
1240 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1241 pkt
->pkt
.secret_key
= sk
;
1242 add_kbnode (sec_root
, new_kbnode( pkt
));
1244 genhelp_factors (misc_key_info
, sec_root
);
1251 * Generate a DSA key
1254 gen_dsa (unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1255 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1256 u32 timestamp
, u32 expireval
, int is_subkey
)
1262 gcry_sexp_t s_parms
, s_key
;
1263 gcry_sexp_t misc_key_info
;
1269 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1271 else if ( nbits
> 3072 )
1274 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1279 nbits
= ((nbits
+ 63) / 64) * 64;
1280 log_info(_("keysize rounded up to %u bits\n"), nbits
);
1284 Figure out a q size based on the key size. FIPS 180-3 says:
1291 2048/256 is an odd pair since there is also a 2048/224 and
1292 3072/256. Matching sizes is not a very exact science.
1294 We'll do 256 qbits for nbits over 2048, 224 for nbits over 1024
1295 but less than 2048, and 160 for 1024 (DSA1).
1300 else if ( nbits
> 1024)
1306 log_info (_("WARNING: some OpenPGP programs can't"
1307 " handle a DSA key with this digest size\n"));
1309 rc
= gcry_sexp_build (&s_parms
, NULL
,
1310 "(genkey(dsa(nbits %d)(qbits %d)))",
1311 (int)nbits
, (int)qbits
);
1313 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1315 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1316 gcry_sexp_release (s_parms
);
1319 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1323 sk
= xmalloc_clear( sizeof *sk
);
1324 pk
= xmalloc_clear( sizeof *pk
);
1325 sk
->timestamp
= pk
->timestamp
= timestamp
;
1326 sk
->version
= pk
->version
= 4;
1328 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1329 sk
->pubkey_algo
= pk
->pubkey_algo
= PUBKEY_ALGO_DSA
;
1331 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pqgy");
1334 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1335 gcry_sexp_release (s_key
);
1336 free_public_key(pk
);
1337 free_secret_key(sk
);
1340 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pqgyx");
1343 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1344 gcry_sexp_release (s_key
);
1345 free_public_key(pk
);
1346 free_secret_key(sk
);
1349 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1350 gcry_sexp_release (s_key
);
1352 sk
->is_protected
= 0;
1353 sk
->protect
.algo
= 0;
1355 sk
->csum
= checksum_mpi ( sk
->skey
[4] );
1356 if( ret_sk
) /* return an unprotected version of the sk */
1357 *ret_sk
= copy_secret_key( NULL
, sk
);
1359 rc
= genhelp_protect (dek
, s2k
, sk
);
1362 free_public_key (pk
);
1363 free_secret_key (sk
);
1364 gcry_sexp_release (misc_key_info
);
1368 pkt
= xmalloc_clear(sizeof *pkt
);
1369 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1370 pkt
->pkt
.public_key
= pk
;
1371 add_kbnode(pub_root
, new_kbnode( pkt
));
1373 /* Don't know whether it makes sense to have the factors, so for now
1374 * we store them in the secret keyring (but they are not secret)
1375 * p = 2 * q * f1 * f2 * ... * fn
1376 * We store only f1 to f_n-1; fn can be calculated because p and q
1379 pkt
= xmalloc_clear(sizeof *pkt
);
1380 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1381 pkt
->pkt
.secret_key
= sk
;
1382 add_kbnode(sec_root
, new_kbnode( pkt
));
1384 genhelp_factors (misc_key_info
, sec_root
);
1391 * Generate an RSA key.
1394 gen_rsa (int algo
, unsigned nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1395 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1396 u32 timestamp
, u32 expireval
, int is_subkey
)
1402 gcry_sexp_t s_parms
, s_key
;
1404 assert (is_RSA(algo
));
1409 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1414 nbits
= ((nbits
+ 31) / 32) * 32;
1415 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1418 rc
= gcry_sexp_build (&s_parms
, NULL
,
1419 "(genkey(rsa(nbits %d)))",
1422 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1424 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1425 gcry_sexp_release (s_parms
);
1428 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1432 sk
= xmalloc_clear( sizeof *sk
);
1433 pk
= xmalloc_clear( sizeof *pk
);
1434 sk
->timestamp
= pk
->timestamp
= timestamp
;
1435 sk
->version
= pk
->version
= 4;
1438 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1440 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1442 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "ne");
1445 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1446 gcry_sexp_release (s_key
);
1447 free_public_key(pk
);
1448 free_secret_key(sk
);
1451 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
1454 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1455 gcry_sexp_release (s_key
);
1456 free_public_key(pk
);
1457 free_secret_key(sk
);
1460 gcry_sexp_release (s_key
);
1462 sk
->is_protected
= 0;
1463 sk
->protect
.algo
= 0;
1465 sk
->csum
= checksum_mpi (sk
->skey
[2] );
1466 sk
->csum
+= checksum_mpi (sk
->skey
[3] );
1467 sk
->csum
+= checksum_mpi (sk
->skey
[4] );
1468 sk
->csum
+= checksum_mpi (sk
->skey
[5] );
1469 if( ret_sk
) /* return an unprotected version of the sk */
1470 *ret_sk
= copy_secret_key( NULL
, sk
);
1472 rc
= genhelp_protect (dek
, s2k
, sk
);
1475 free_public_key (pk
);
1476 free_secret_key (sk
);
1480 pkt
= xmalloc_clear(sizeof *pkt
);
1481 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1482 pkt
->pkt
.public_key
= pk
;
1483 add_kbnode(pub_root
, new_kbnode( pkt
));
1485 pkt
= xmalloc_clear(sizeof *pkt
);
1486 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1487 pkt
->pkt
.secret_key
= sk
;
1488 add_kbnode(sec_root
, new_kbnode( pkt
));
1496 * return 0 on error or the multiplier
1499 check_valid_days( const char *s
)
1509 return 0; /* e.g. "2323wc" */
1510 if( *s
== 'd' || *s
== 'D' )
1512 if( *s
== 'w' || *s
== 'W' )
1514 if( *s
== 'm' || *s
== 'M' )
1516 if( *s
== 'y' || *s
== 'Y' )
1523 print_key_flags(int flags
)
1525 if(flags
&PUBKEY_USAGE_SIG
)
1526 tty_printf("%s ",_("Sign"));
1528 if(flags
&PUBKEY_USAGE_CERT
)
1529 tty_printf("%s ",_("Certify"));
1531 if(flags
&PUBKEY_USAGE_ENC
)
1532 tty_printf("%s ",_("Encrypt"));
1534 if(flags
&PUBKEY_USAGE_AUTH
)
1535 tty_printf("%s ",_("Authenticate"));
1539 /* Returns the key flags */
1541 ask_key_flags(int algo
,int subkey
)
1543 /* TRANSLATORS: Please use only plain ASCII characters for the
1544 translation. If this is not possible use single digits. The
1545 string needs to 8 bytes long. Here is a description of the
1548 s = Toggle signing capability
1549 e = Toggle encryption capability
1550 a = Toggle authentication capability
1553 const char *togglers
=_("SsEeAaQq");
1555 unsigned int current
=0;
1556 unsigned int possible
=openpgp_pk_algo_usage(algo
);
1558 if ( strlen(togglers
) != 8 )
1560 tty_printf ("NOTE: Bad translation at %s:%d. "
1561 "Please report.\n", __FILE__
, __LINE__
);
1562 togglers
= "11223300";
1565 /* Only primary keys may certify. */
1567 possible
&=~PUBKEY_USAGE_CERT
;
1569 /* Preload the current set with the possible set, minus
1570 authentication, since nobody really uses auth yet. */
1571 current
=possible
&~PUBKEY_USAGE_AUTH
;
1576 tty_printf(_("Possible actions for a %s key: "),
1577 gcry_pk_algo_name (algo
));
1578 print_key_flags(possible
);
1580 tty_printf(_("Current allowed actions: "));
1581 print_key_flags(current
);
1584 if(possible
&PUBKEY_USAGE_SIG
)
1585 tty_printf(_(" (%c) Toggle the sign capability\n"),
1587 if(possible
&PUBKEY_USAGE_ENC
)
1588 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1590 if(possible
&PUBKEY_USAGE_AUTH
)
1591 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1594 tty_printf(_(" (%c) Finished\n"),togglers
[6]);
1598 answer
= cpr_get("keygen.flags",_("Your selection? "));
1601 if(strlen(answer
)>1)
1602 tty_printf(_("Invalid selection.\n"));
1603 else if(*answer
=='\0' || *answer
==togglers
[6] || *answer
==togglers
[7])
1605 else if((*answer
==togglers
[0] || *answer
==togglers
[1])
1606 && possible
&PUBKEY_USAGE_SIG
)
1608 if(current
&PUBKEY_USAGE_SIG
)
1609 current
&=~PUBKEY_USAGE_SIG
;
1611 current
|=PUBKEY_USAGE_SIG
;
1613 else if((*answer
==togglers
[2] || *answer
==togglers
[3])
1614 && possible
&PUBKEY_USAGE_ENC
)
1616 if(current
&PUBKEY_USAGE_ENC
)
1617 current
&=~PUBKEY_USAGE_ENC
;
1619 current
|=PUBKEY_USAGE_ENC
;
1621 else if((*answer
==togglers
[4] || *answer
==togglers
[5])
1622 && possible
&PUBKEY_USAGE_AUTH
)
1624 if(current
&PUBKEY_USAGE_AUTH
)
1625 current
&=~PUBKEY_USAGE_AUTH
;
1627 current
|=PUBKEY_USAGE_AUTH
;
1630 tty_printf(_("Invalid selection.\n"));
1639 /* Ask for an algorithm. The function returns the algorithm id to
1640 * create. If ADDMODE is false the function won't show an option to
1641 * create the primary and subkey combined and won't set R_USAGE
1642 * either. If a combined algorithm has been selected, the subkey
1643 * algorithm is stored at R_SUBKEY_ALGO. */
1645 ask_algo (int addmode
, int *r_subkey_algo
, unsigned int *r_usage
)
1652 r_subkey_algo
= &dummy_algo
;
1654 tty_printf (_("Please select what kind of key you want:\n"));
1657 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1659 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1661 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1662 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1666 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1667 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1671 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1672 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1679 answer
= cpr_get ("keygen.algo", _("Your selection? "));
1681 algo
= *answer
? atoi (answer
) : 1;
1683 if (algo
== 1 && !addmode
)
1685 algo
= PUBKEY_ALGO_RSA
;
1686 *r_subkey_algo
= PUBKEY_ALGO_RSA
;
1689 else if (algo
== 2 && !addmode
)
1691 algo
= PUBKEY_ALGO_DSA
;
1692 *r_subkey_algo
= PUBKEY_ALGO_ELGAMAL_E
;
1697 algo
= PUBKEY_ALGO_DSA
;
1698 *r_usage
= PUBKEY_USAGE_SIG
;
1703 algo
= PUBKEY_ALGO_RSA
;
1704 *r_usage
= PUBKEY_USAGE_SIG
;
1707 else if (algo
== 5 && addmode
)
1709 algo
= PUBKEY_ALGO_ELGAMAL_E
;
1710 *r_usage
= PUBKEY_USAGE_ENC
;
1713 else if (algo
== 6 && addmode
)
1715 algo
= PUBKEY_ALGO_RSA
;
1716 *r_usage
= PUBKEY_USAGE_ENC
;
1719 else if (algo
== 7 && opt
.expert
)
1721 algo
= PUBKEY_ALGO_DSA
;
1722 *r_usage
= ask_key_flags (algo
, addmode
);
1725 else if (algo
== 8 && opt
.expert
)
1727 algo
= PUBKEY_ALGO_RSA
;
1728 *r_usage
= ask_key_flags (algo
, addmode
);
1732 tty_printf (_("Invalid selection.\n"));
1739 /* Ask for the key size. ALGO is the algorithjm. If PRIMARY_KEYSIZE
1740 is not 0, the function asks for the size of the encryption
1743 ask_keysize (int algo
, unsigned int primary_keysize
)
1745 unsigned int nbits
, min
, def
=2048, max
=4096;
1746 int for_subkey
= !!primary_keysize
;
1754 if (primary_keysize
&& !opt
.expert
)
1756 /* Deduce the subkey size from the primary key size. */
1757 if (algo
== PUBKEY_ALGO_DSA
&& primary_keysize
> 3072)
1758 nbits
= 3072; /* For performance reasons we don't support more
1759 than 3072 bit DSA. However we won't see this
1760 case anyway because DSA can't be used as an
1761 encryption subkey ;-). */
1763 nbits
= primary_keysize
;
1770 case PUBKEY_ALGO_DSA
:
1775 case PUBKEY_ALGO_RSA
:
1780 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1781 gcry_pk_algo_name (algo
), min
, max
);
1785 char *prompt
, *answer
;
1788 prompt
= xasprintf (_("What keysize do you want "
1789 "for the subkey? (%u) "), def
);
1791 prompt
= xasprintf (_("What keysize do you want? (%u) "), def
);
1792 answer
= cpr_get ("keygen.size", prompt
);
1794 nbits
= *answer
? atoi (answer
): def
;
1798 if(nbits
<min
|| nbits
>max
)
1799 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1800 gcry_pk_algo_name (algo
), min
, max
);
1805 tty_printf(_("Requested keysize is %u bits\n"), nbits
);
1808 if( algo
== PUBKEY_ALGO_DSA
&& (nbits
% 64) )
1810 nbits
= ((nbits
+ 63) / 64) * 64;
1812 tty_printf(_("rounded up to %u bits\n"), nbits
);
1814 else if( (nbits
% 32) )
1816 nbits
= ((nbits
+ 31) / 32) * 32;
1818 tty_printf(_("rounded up to %u bits\n"), nbits
);
1826 * Parse an expire string and return its value in seconds.
1827 * Returns (u32)-1 on error.
1828 * This isn't perfect since scan_isodatestr returns unix time, and
1829 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1830 * Because of this, we only permit setting expirations up to 2106, but
1831 * OpenPGP could theoretically allow up to 2242. I think we'll all
1832 * just cope for the next few years until we get a 64-bit time_t or
1836 parse_expire_string( const char *string
)
1841 u32 curtime
= make_timestamp ();
1846 else if (!strncmp (string
, "seconds=", 8))
1847 seconds
= atoi (string
+8);
1848 else if ((abs_date
= scan_isodatestr(string
))
1849 && (abs_date
+86400/2) > curtime
)
1850 seconds
= (abs_date
+86400/2) - curtime
;
1851 else if ((tt
= isotime2epoch (string
)) != (time_t)(-1))
1852 seconds
= (u32
)tt
- curtime
;
1853 else if ((mult
= check_valid_days (string
)))
1854 seconds
= atoi (string
) * 86400L * mult
;
1856 seconds
= (u32
)(-1);
1861 /* Parsean Creation-Date string which is either "1986-04-26" or
1862 "19860426T042640". Returns 0 on error. */
1864 parse_creation_string (const char *string
)
1870 else if ( !strncmp (string
, "seconds=", 8) )
1871 seconds
= atoi (string
+8);
1872 else if ( !(seconds
= scan_isodatestr (string
)))
1874 time_t tmp
= isotime2epoch (string
);
1875 seconds
= (tmp
== (time_t)(-1))? 0 : tmp
;
1881 /* object == 0 for a key, and 1 for a sig */
1883 ask_expire_interval(int object
,const char *def_expire
)
1893 tty_printf(_("Please specify how long the key should be valid.\n"
1894 " 0 = key does not expire\n"
1895 " <n> = key expires in n days\n"
1896 " <n>w = key expires in n weeks\n"
1897 " <n>m = key expires in n months\n"
1898 " <n>y = key expires in n years\n"));
1904 tty_printf(_("Please specify how long the signature should be valid.\n"
1905 " 0 = signature does not expire\n"
1906 " <n> = signature expires in n days\n"
1907 " <n>w = signature expires in n weeks\n"
1908 " <n>m = signature expires in n months\n"
1909 " <n>y = signature expires in n years\n"));
1916 /* Note: The elgamal subkey for DSA has no expiration date because
1917 * it must be signed with the DSA key and this one has the expiration
1923 u32 curtime
=make_timestamp();
1927 answer
= cpr_get("keygen.valid",_("Key is valid for? (0) "));
1932 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1933 /* This will actually end up larger than necessary because
1934 of the 2 bytes for '%s' */
1935 prompt
=xmalloc(strlen(PROMPTSTRING
)+strlen(def_expire
)+1);
1936 sprintf(prompt
,PROMPTSTRING
,def_expire
);
1939 answer
= cpr_get("siggen.valid",prompt
);
1943 answer
=xstrdup(def_expire
);
1946 trim_spaces(answer
);
1947 interval
= parse_expire_string( answer
);
1948 if( interval
== (u32
)-1 )
1950 tty_printf(_("invalid value\n"));
1956 tty_printf((object
==0)
1957 ? _("Key does not expire at all\n")
1958 : _("Signature does not expire at all\n"));
1962 tty_printf(object
==0
1963 ? _("Key expires at %s\n")
1964 : _("Signature expires at %s\n"),
1965 asctimestamp((ulong
)(curtime
+ interval
) ) );
1966 #if SIZEOF_TIME_T <= 4
1967 if ( (time_t)((ulong
)(curtime
+interval
)) < 0 )
1968 tty_printf (_("Your system can't display dates beyond 2038.\n"
1969 "However, it will be correctly handled up to"
1972 #endif /*SIZEOF_TIME_T*/
1973 if ( (time_t)((unsigned long)(curtime
+interval
)) < curtime
)
1975 tty_printf (_("invalid value\n"));
1980 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1981 _("Is this correct? (y/N) ")) )
1992 u32 x
= ask_expire_interval(0,NULL
);
1993 return x
? make_timestamp() + x
: 0;
1998 ask_user_id( int mode
)
2001 char *aname
, *acomment
, *amail
, *uid
;
2005 /* TRANSLATORS: This is the new string telling the user what
2006 gpg is now going to do (i.e. ask for the parts of the user
2007 ID). Note that if you do not tyranslated this string, a
2008 different string will be used used, which might still have
2009 a correct transaltion. */
2012 "GnuPG needs to construct a user ID to identify your key.\n"
2014 const char *s2
= _(s1
);
2016 if (!strcmp (s1
, s2
))
2018 /* There is no translation for the string thus we to use
2019 the old info text. gettext has no way to tell whether
2020 a translation is actually available, thus we need to
2021 to compare again. */
2022 /* TRANSLATORS: This string is in general not anymore used
2023 but you should keep your existing translation. In case
2024 the new string is not translated this old string will
2026 const char *s3
= N_("\n"
2027 "You need a user ID to identify your key; "
2028 "the software constructs the user ID\n"
2029 "from the Real Name, Comment and Email Address in this form:\n"
2030 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2031 const char *s4
= _(s3
);
2032 if (strcmp (s3
, s4
))
2033 s2
= s3
; /* A translation exists - use it. */
2035 tty_printf ("%s", s2
) ;
2037 uid
= aname
= acomment
= amail
= NULL
;
2045 aname
= cpr_get("keygen.name",_("Real name: "));
2049 if( opt
.allow_freeform_uid
)
2052 if( strpbrk( aname
, "<>" ) )
2053 tty_printf(_("Invalid character in name\n"));
2054 else if( digitp(aname
) )
2055 tty_printf(_("Name may not start with a digit\n"));
2056 else if( strlen(aname
) < 5 )
2057 tty_printf(_("Name must be at least 5 characters long\n"));
2065 amail
= cpr_get("keygen.email",_("Email address: "));
2068 if( !*amail
|| opt
.allow_freeform_uid
)
2069 break; /* no email address is okay */
2070 else if ( !is_valid_mailbox (amail
) )
2071 tty_printf(_("Not a valid email address\n"));
2079 acomment
= cpr_get("keygen.comment",_("Comment: "));
2080 trim_spaces(acomment
);
2083 break; /* no comment is okay */
2084 else if( strpbrk( acomment
, "()" ) )
2085 tty_printf(_("Invalid character in comment\n"));
2093 uid
= p
= xmalloc(strlen(aname
)+strlen(amail
)+strlen(acomment
)+12+10);
2094 p
= stpcpy(p
, aname
);
2096 p
= stpcpy(stpcpy(stpcpy(p
," ("), acomment
),")");
2098 p
= stpcpy(stpcpy(stpcpy(p
," <"), amail
),">");
2100 /* Append a warning if the RNG is switched into fake mode. */
2101 if ( random_is_faked () )
2102 strcpy(p
, " (insecure!)" );
2104 /* print a note in case that UTF8 mapping has to be done */
2105 for(p
=uid
; *p
; p
++ ) {
2107 tty_printf(_("You are using the `%s' character set.\n"),
2108 get_native_charset() );
2113 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid
);
2114 /* fixme: add a warning if this user-id already exists */
2115 if( !*amail
&& !opt
.allow_freeform_uid
2116 && (strchr( aname
, '@' ) || strchr( acomment
, '@'))) {
2118 tty_printf(_("Please don't put the email address "
2119 "into the real name or the comment\n") );
2123 /* TRANSLATORS: These are the allowed answers in
2124 lower and uppercase. Below you will find the matching
2125 string which should be translated accordingly and the
2126 letter changed to match the one in the answer string.
2131 o = Okay (ready, continue)
2134 const char *ansstr
= _("NnCcEeOoQq");
2136 if( strlen(ansstr
) != 10 )
2138 if( cpr_enabled() ) {
2139 answer
= xstrdup(ansstr
+6);
2143 answer
= cpr_get("keygen.userid.cmd", fail
?
2144 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2145 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2148 if( strlen(answer
) > 1 )
2150 else if( *answer
== ansstr
[0] || *answer
== ansstr
[1] ) {
2151 xfree(aname
); aname
= NULL
;
2154 else if( *answer
== ansstr
[2] || *answer
== ansstr
[3] ) {
2155 xfree(acomment
); acomment
= NULL
;
2158 else if( *answer
== ansstr
[4] || *answer
== ansstr
[5] ) {
2159 xfree(amail
); amail
= NULL
;
2162 else if( *answer
== ansstr
[6] || *answer
== ansstr
[7] ) {
2164 tty_printf(_("Please correct the error first\n"));
2167 xfree(aname
); aname
= NULL
;
2168 xfree(acomment
); acomment
= NULL
;
2169 xfree(amail
); amail
= NULL
;
2173 else if( *answer
== ansstr
[8] || *answer
== ansstr
[9] ) {
2174 xfree(aname
); aname
= NULL
;
2175 xfree(acomment
); acomment
= NULL
;
2176 xfree(amail
); amail
= NULL
;
2177 xfree(uid
); uid
= NULL
;
2183 if( !amail
&& !acomment
&& !amail
)
2185 xfree(uid
); uid
= NULL
;
2188 char *p
= native_to_utf8( uid
);
2196 /* MODE 0 - standard
2197 1 - Ask for passphrase of the card backup key. */
2199 do_ask_passphrase (STRING2KEY
**ret_s2k
, int mode
, int *r_canceled
)
2203 const char *errtext
= NULL
;
2204 const char *custdesc
= NULL
;
2206 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2209 custdesc
= _("Please enter a passphrase to protect the off-card "
2210 "backup of the new encryption key.");
2212 s2k
= xmalloc_secure( sizeof *s2k
);
2214 s2k
->mode
= opt
.s2k_mode
;
2215 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2216 dek
= passphrase_to_dek_ext (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2217 errtext
, custdesc
, NULL
, r_canceled
);
2218 if (!dek
&& *r_canceled
) {
2219 xfree(dek
); dek
= NULL
;
2220 xfree(s2k
); s2k
= NULL
;
2224 errtext
= N_("passphrase not correctly repeated; try again");
2225 tty_printf(_("%s.\n"), _(errtext
));
2227 else if( !dek
->keylen
) {
2228 xfree(dek
); dek
= NULL
;
2229 xfree(s2k
); s2k
= NULL
;
2231 "You don't want a passphrase - this is probably a *bad* idea!\n"
2232 "I will do it anyway. You can change your passphrase at any time,\n"
2233 "using this program with the option \"--edit-key\".\n\n"));
2244 /* Basic key generation. Here we divert to the actual generation
2245 routines based on the requested algorithm. */
2247 do_create (int algo
, unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
,
2248 DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
**sk
,
2249 u32 timestamp
, u32 expiredate
, int is_subkey
)
2255 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2256 "some other action (type on the keyboard, move the mouse, utilize the\n"
2257 "disks) during the prime generation; this gives the random number\n"
2258 "generator a better chance to gain enough entropy.\n") );
2260 if( algo
== PUBKEY_ALGO_ELGAMAL_E
)
2261 rc
= gen_elg(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2262 timestamp
, expiredate
, is_subkey
);
2263 else if( algo
== PUBKEY_ALGO_DSA
)
2264 rc
= gen_dsa(nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2265 timestamp
, expiredate
, is_subkey
);
2266 else if( algo
== PUBKEY_ALGO_RSA
)
2267 rc
= gen_rsa(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2268 timestamp
, expiredate
, is_subkey
);
2277 * Generate a new user id packet, or return NULL if canceled
2286 p
= ask_user_id( 1 );
2290 uid
= xmalloc_clear( sizeof *uid
+ n
);
2292 strcpy(uid
->name
, p
);
2299 release_parameter_list( struct para_data_s
*r
)
2301 struct para_data_s
*r2
;
2303 for( ; r
; r
= r2
) {
2305 if( r
->key
== pPASSPHRASE_DEK
)
2307 else if( r
->key
== pPASSPHRASE_S2K
)
2314 static struct para_data_s
*
2315 get_parameter( struct para_data_s
*para
, enum para_name key
)
2317 struct para_data_s
*r
;
2319 for( r
= para
; r
&& r
->key
!= key
; r
= r
->next
)
2325 get_parameter_value( struct para_data_s
*para
, enum para_name key
)
2327 struct para_data_s
*r
= get_parameter( para
, key
);
2328 return (r
&& *r
->u
.value
)? r
->u
.value
: NULL
;
2332 get_parameter_algo( struct para_data_s
*para
, enum para_name key
)
2335 struct para_data_s
*r
= get_parameter( para
, key
);
2338 if( digitp( r
->u
.value
) )
2339 i
= atoi( r
->u
.value
);
2340 else if ( !strcmp ( r
->u
.value
, "ELG-E")
2341 || !strcmp ( r
->u
.value
, "ELG") )
2344 i
= gcry_pk_map_name (r
->u
.value
);
2345 if (i
== PUBKEY_ALGO_RSA_E
|| i
== PUBKEY_ALGO_RSA_S
)
2346 i
= 0; /* we don't want to allow generation of these algorithms */
2351 * Parse the usage parameter and set the keyflags. Returns -1 on
2352 * error, 0 for no usage given or 1 for usage available.
2355 parse_parameter_usage (const char *fname
,
2356 struct para_data_s
*para
, enum para_name key
)
2358 struct para_data_s
*r
= get_parameter( para
, key
);
2363 return 0; /* none (this is an optional parameter)*/
2367 while ( (p
= strsep (&pn
, " \t,")) ) {
2370 else if ( !ascii_strcasecmp (p
, "sign") )
2371 use
|= PUBKEY_USAGE_SIG
;
2372 else if ( !ascii_strcasecmp (p
, "encrypt") )
2373 use
|= PUBKEY_USAGE_ENC
;
2374 else if ( !ascii_strcasecmp (p
, "auth") )
2375 use
|= PUBKEY_USAGE_AUTH
;
2377 log_error("%s:%d: invalid usage list\n", fname
, r
->lnr
);
2378 return -1; /* error */
2386 parse_revocation_key (const char *fname
,
2387 struct para_data_s
*para
, enum para_name key
)
2389 struct para_data_s
*r
= get_parameter( para
, key
);
2390 struct revocation_key revkey
;
2395 return 0; /* none (this is an optional parameter) */
2400 revkey
.algid
=atoi(pn
);
2404 /* Skip to the fpr */
2405 while(*pn
&& *pn
!=':')
2413 for(i
=0;i
<MAX_FINGERPRINT_LEN
&& *pn
;i
++,pn
+=2)
2415 int c
=hextobyte(pn
);
2422 /* skip to the tag */
2423 while(*pn
&& *pn
!='s' && *pn
!='S')
2426 if(ascii_strcasecmp(pn
,"sensitive")==0)
2429 memcpy(&r
->u
.revkey
,&revkey
,sizeof(struct revocation_key
));
2434 log_error("%s:%d: invalid revocation key\n", fname
, r
->lnr
);
2435 return -1; /* error */
2440 get_parameter_u32( struct para_data_s
*para
, enum para_name key
)
2442 struct para_data_s
*r
= get_parameter( para
, key
);
2446 if( r
->key
== pKEYCREATIONDATE
)
2447 return r
->u
.creation
;
2448 if( r
->key
== pKEYEXPIRE
|| r
->key
== pSUBKEYEXPIRE
)
2450 if( r
->key
== pKEYUSAGE
|| r
->key
== pSUBKEYUSAGE
)
2453 return (unsigned int)strtoul( r
->u
.value
, NULL
, 10 );
2457 get_parameter_uint( struct para_data_s
*para
, enum para_name key
)
2459 return get_parameter_u32( para
, key
);
2463 get_parameter_dek( struct para_data_s
*para
, enum para_name key
)
2465 struct para_data_s
*r
= get_parameter( para
, key
);
2466 return r
? r
->u
.dek
: NULL
;
2470 get_parameter_s2k( struct para_data_s
*para
, enum para_name key
)
2472 struct para_data_s
*r
= get_parameter( para
, key
);
2473 return r
? r
->u
.s2k
: NULL
;
2476 static struct revocation_key
*
2477 get_parameter_revkey( struct para_data_s
*para
, enum para_name key
)
2479 struct para_data_s
*r
= get_parameter( para
, key
);
2480 return r
? &r
->u
.revkey
: NULL
;
2484 proc_parameter_file( struct para_data_s
*para
, const char *fname
,
2485 struct output_control_s
*outctrl
, int card
)
2487 struct para_data_s
*r
;
2488 const char *s1
, *s2
, *s3
;
2491 int have_user_id
=0,err
,algo
;
2493 /* Check that we have all required parameters. */
2494 r
= get_parameter( para
, pKEYTYPE
);
2497 algo
=get_parameter_algo(para
,pKEYTYPE
);
2498 if (openpgp_pk_test_algo2 (algo
, PUBKEY_USAGE_SIG
))
2500 log_error ("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2506 log_error ("%s: no Key-Type specified\n",fname
);
2510 err
= parse_parameter_usage (fname
, para
, pKEYUSAGE
);
2513 /* Default to algo capabilities if key-usage is not provided */
2514 r
= xmalloc_clear(sizeof(*r
));
2516 r
->u
.usage
= openpgp_pk_algo_usage(algo
);
2524 r
= get_parameter (para
, pKEYUSAGE
);
2525 if (r
&& (r
->u
.usage
& ~openpgp_pk_algo_usage (algo
)))
2527 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2528 fname
, r
->lnr
, algo
);
2533 r
= get_parameter( para
, pSUBKEYTYPE
);
2536 algo
= get_parameter_algo (para
, pSUBKEYTYPE
);
2537 if (openpgp_pk_test_algo (algo
))
2539 log_error ("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2543 err
= parse_parameter_usage (fname
, para
, pSUBKEYUSAGE
);
2546 /* Default to algo capabilities if subkey-usage is not
2548 r
= xmalloc_clear (sizeof(*r
));
2549 r
->key
= pSUBKEYUSAGE
;
2550 r
->u
.usage
= openpgp_pk_algo_usage (algo
);
2558 r
= get_parameter (para
, pSUBKEYUSAGE
);
2559 if (r
&& (r
->u
.usage
& ~openpgp_pk_algo_usage (algo
)))
2561 log_error ("%s:%d: specified Subkey-Usage not allowed"
2562 " for algo %d\n", fname
, r
->lnr
, algo
);
2569 if( get_parameter_value( para
, pUSERID
) )
2573 /* create the formatted user ID */
2574 s1
= get_parameter_value( para
, pNAMEREAL
);
2575 s2
= get_parameter_value( para
, pNAMECOMMENT
);
2576 s3
= get_parameter_value( para
, pNAMEEMAIL
);
2577 if( s1
|| s2
|| s3
)
2579 n
= (s1
?strlen(s1
):0) + (s2
?strlen(s2
):0) + (s3
?strlen(s3
):0);
2580 r
= xmalloc_clear( sizeof *r
+ n
+ 20 );
2586 p
= stpcpy(stpcpy(stpcpy(p
," ("), s2
),")");
2588 p
= stpcpy(stpcpy(stpcpy(p
," <"), s3
),">");
2597 log_error("%s: no User-ID specified\n",fname
);
2601 /* Set preferences, if any. */
2602 keygen_set_std_prefs(get_parameter_value( para
, pPREFERENCES
), 0);
2604 /* Set keyserver, if any. */
2605 s1
=get_parameter_value( para
, pKEYSERVER
);
2608 struct keyserver_spec
*spec
;
2610 spec
=parse_keyserver_uri(s1
,1,NULL
,0);
2613 free_keyserver_spec(spec
);
2614 opt
.def_keyserver_url
=s1
;
2618 log_error("%s:%d: invalid keyserver url\n", fname
, r
->lnr
);
2623 /* Set revoker, if any. */
2624 if (parse_revocation_key (fname
, para
, pREVOKER
))
2627 /* Make DEK and S2K from the Passphrase. */
2628 if (outctrl
->ask_passphrase
)
2630 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2631 feature is required so that GUIs are able to do a key
2632 creation but have gpg-agent ask for the passphrase. */
2637 dek
= do_ask_passphrase (&s2k
, 0, &canceled
);
2640 r
= xmalloc_clear( sizeof *r
);
2641 r
->key
= pPASSPHRASE_DEK
;
2645 r
= xmalloc_clear( sizeof *r
);
2646 r
->key
= pPASSPHRASE_S2K
;
2654 log_error ("%s:%d: key generation canceled\n", fname
, r
->lnr
);
2660 r
= get_parameter( para
, pPASSPHRASE
);
2661 if ( r
&& *r
->u
.value
)
2663 /* We have a plain text passphrase - create a DEK from it.
2664 * It is a little bit ridiculous to keep it in secure memory
2665 * but because we do this always, why not here. */
2669 s2k
= xmalloc_secure ( sizeof *s2k
);
2670 s2k
->mode
= opt
.s2k_mode
;
2671 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2672 set_next_passphrase ( r
->u
.value
);
2673 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2675 set_next_passphrase (NULL
);
2677 memset (r
->u
.value
, 0, strlen(r
->u
.value
));
2679 r
= xmalloc_clear (sizeof *r
);
2680 r
->key
= pPASSPHRASE_S2K
;
2684 r
= xmalloc_clear (sizeof *r
);
2685 r
->key
= pPASSPHRASE_DEK
;
2692 /* Make KEYCREATIONDATE from Creation-Date. */
2693 r
= get_parameter (para
, pCREATIONDATE
);
2694 if (r
&& *r
->u
.value
)
2698 seconds
= parse_creation_string (r
->u
.value
);
2701 log_error ("%s:%d: invalid creation date\n", fname
, r
->lnr
);
2704 r
->u
.creation
= seconds
;
2705 r
->key
= pKEYCREATIONDATE
; /* Change that entry. */
2708 /* Make KEYEXPIRE from Expire-Date. */
2709 r
= get_parameter( para
, pEXPIREDATE
);
2710 if( r
&& *r
->u
.value
)
2714 seconds
= parse_expire_string( r
->u
.value
);
2715 if( seconds
== (u32
)-1 )
2717 log_error("%s:%d: invalid expire date\n", fname
, r
->lnr
);
2720 r
->u
.expire
= seconds
;
2721 r
->key
= pKEYEXPIRE
; /* change hat entry */
2722 /* also set it for the subkey */
2723 r
= xmalloc_clear( sizeof *r
+ 20 );
2724 r
->key
= pSUBKEYEXPIRE
;
2725 r
->u
.expire
= seconds
;
2730 if( !!outctrl
->pub
.newfname
^ !!outctrl
->sec
.newfname
) {
2731 log_error("%s:%d: only one ring name is set\n", fname
, outctrl
->lnr
);
2735 do_generate_keypair( para
, outctrl
, card
);
2741 * Kludge to allow non interactive key generation controlled
2742 * by a parameter file.
2743 * Note, that string parameters are expected to be in UTF-8
2746 read_parameter_file( const char *fname
)
2748 static struct { const char *name
;
2751 { "Key-Type", pKEYTYPE
},
2752 { "Key-Length", pKEYLENGTH
},
2753 { "Key-Usage", pKEYUSAGE
},
2754 { "Subkey-Type", pSUBKEYTYPE
},
2755 { "Subkey-Length", pSUBKEYLENGTH
},
2756 { "Subkey-Usage", pSUBKEYUSAGE
},
2757 { "Name-Real", pNAMEREAL
},
2758 { "Name-Email", pNAMEEMAIL
},
2759 { "Name-Comment", pNAMECOMMENT
},
2760 { "Expire-Date", pEXPIREDATE
},
2761 { "Creation-Date", pCREATIONDATE
},
2762 { "Passphrase", pPASSPHRASE
},
2763 { "Preferences", pPREFERENCES
},
2764 { "Revoker", pREVOKER
},
2765 { "Handle", pHANDLE
},
2766 { "Keyserver", pKEYSERVER
},
2771 unsigned int maxlen
, nline
;
2774 const char *err
= NULL
;
2775 struct para_data_s
*para
, *r
;
2777 struct output_control_s outctrl
;
2779 memset( &outctrl
, 0, sizeof( outctrl
) );
2780 outctrl
.pub
.afx
= new_armor_context ();
2781 outctrl
.sec
.afx
= new_armor_context ();
2783 if( !fname
|| !*fname
)
2786 fp
= iobuf_open (fname
);
2787 if (fp
&& is_secured_file (iobuf_get_fd (fp
)))
2794 log_error (_("can't open `%s': %s\n"), fname
, strerror(errno
) );
2797 iobuf_ioctl (fp
, 3, 1, NULL
); /* No file caching. */
2804 while ( iobuf_read_line (fp
, &line
, &nline
, &maxlen
) ) {
2805 char *keyword
, *value
;
2809 err
= "line too long";
2812 for( p
= line
; isspace(*(byte
*)p
); p
++ )
2814 if( !*p
|| *p
== '#' )
2817 if( *keyword
== '%' ) {
2818 for( ; !isspace(*(byte
*)p
); p
++ )
2822 for( ; isspace(*(byte
*)p
); p
++ )
2825 trim_trailing_ws( value
, strlen(value
) );
2826 if( !ascii_strcasecmp( keyword
, "%echo" ) )
2827 log_info("%s\n", value
);
2828 else if( !ascii_strcasecmp( keyword
, "%dry-run" ) )
2830 else if( !ascii_strcasecmp( keyword
, "%ask-passphrase" ) )
2831 outctrl
.ask_passphrase
= 1;
2832 else if( !ascii_strcasecmp( keyword
, "%no-ask-passphrase" ) )
2833 outctrl
.ask_passphrase
= 0;
2834 else if( !ascii_strcasecmp( keyword
, "%commit" ) ) {
2836 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2837 print_status_key_not_created
2838 (get_parameter_value (para
, pHANDLE
));
2839 release_parameter_list( para
);
2842 else if( !ascii_strcasecmp( keyword
, "%pubring" ) ) {
2843 if( outctrl
.pub
.fname
&& !strcmp( outctrl
.pub
.fname
, value
) )
2844 ; /* still the same file - ignore it */
2846 xfree( outctrl
.pub
.newfname
);
2847 outctrl
.pub
.newfname
= xstrdup( value
);
2848 outctrl
.use_files
= 1;
2851 else if( !ascii_strcasecmp( keyword
, "%secring" ) ) {
2852 if( outctrl
.sec
.fname
&& !strcmp( outctrl
.sec
.fname
, value
) )
2853 ; /* still the same file - ignore it */
2855 xfree( outctrl
.sec
.newfname
);
2856 outctrl
.sec
.newfname
= xstrdup( value
);
2857 outctrl
.use_files
= 1;
2861 log_info("skipping control `%s' (%s)\n", keyword
, value
);
2868 if( !(p
= strchr( p
, ':' )) || p
== keyword
) {
2869 err
= "missing colon";
2874 for( ; isspace(*(byte
*)p
); p
++ )
2877 err
= "missing argument";
2881 trim_trailing_ws( value
, strlen(value
) );
2883 for(i
=0; keywords
[i
].name
; i
++ ) {
2884 if( !ascii_strcasecmp( keywords
[i
].name
, keyword
) )
2887 if( !keywords
[i
].name
) {
2888 err
= "unknown keyword";
2891 if( keywords
[i
].key
!= pKEYTYPE
&& !para
) {
2892 err
= "parameter block does not start with \"Key-Type\"";
2896 if( keywords
[i
].key
== pKEYTYPE
&& para
) {
2898 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2899 print_status_key_not_created
2900 (get_parameter_value (para
, pHANDLE
));
2901 release_parameter_list( para
);
2905 for( r
= para
; r
; r
= r
->next
) {
2906 if( r
->key
== keywords
[i
].key
)
2910 err
= "duplicate keyword";
2914 r
= xmalloc_clear( sizeof *r
+ strlen( value
) );
2916 r
->key
= keywords
[i
].key
;
2917 strcpy( r
->u
.value
, value
);
2922 log_error("%s:%d: %s\n", fname
, lnr
, err
);
2923 else if( iobuf_error (fp
) ) {
2924 log_error("%s:%d: read error\n", fname
, lnr
);
2928 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2929 print_status_key_not_created (get_parameter_value (para
, pHANDLE
));
2932 if( outctrl
.use_files
) { /* close open streams */
2933 iobuf_close( outctrl
.pub
.stream
);
2934 iobuf_close( outctrl
.sec
.stream
);
2936 /* Must invalidate that ugly cache to actually close it. */
2937 if (outctrl
.pub
.fname
)
2938 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.pub
.fname
);
2939 if (outctrl
.sec
.fname
)
2940 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.sec
.fname
);
2942 xfree( outctrl
.pub
.fname
);
2943 xfree( outctrl
.pub
.newfname
);
2944 xfree( outctrl
.sec
.fname
);
2945 xfree( outctrl
.sec
.newfname
);
2948 release_parameter_list( para
);
2950 release_armor_context (outctrl
.pub
.afx
);
2951 release_armor_context (outctrl
.sec
.afx
);
2956 * Generate a keypair (fname is only used in batch mode) If
2957 * CARD_SERIALNO is not NULL the function will create the keys on an
2958 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
2959 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
2960 * generate in software, imported to the card and a backup file
2961 * written to directory given by this argument .
2964 generate_keypair (const char *fname
, const char *card_serialno
,
2965 const char *backup_encryption_dir
)
2975 struct para_data_s
*para
= NULL
;
2976 struct para_data_s
*r
;
2977 struct output_control_s outctrl
;
2980 memset( &outctrl
, 0, sizeof( outctrl
) );
2982 if (opt
.batch
&& card_serialno
)
2984 /* We don't yet support unattended key generation. */
2985 log_error (_("can't do this in batch mode\n"));
2991 read_parameter_file( fname
);
2997 #ifdef ENABLE_CARD_SUPPORT
2998 r
= xcalloc (1, sizeof *r
+ strlen (card_serialno
) );
3000 strcpy( r
->u
.value
, card_serialno
);
3004 algo
= PUBKEY_ALGO_RSA
;
3006 r
= xcalloc (1, sizeof *r
+ 20 );
3008 sprintf( r
->u
.value
, "%d", algo
);
3011 r
= xcalloc (1, sizeof *r
+ 20 );
3013 strcpy (r
->u
.value
, "sign");
3017 r
= xcalloc (1, sizeof *r
+ 20 );
3018 r
->key
= pSUBKEYTYPE
;
3019 sprintf( r
->u
.value
, "%d", algo
);
3022 r
= xcalloc (1, sizeof *r
+ 20 );
3023 r
->key
= pSUBKEYUSAGE
;
3024 strcpy (r
->u
.value
, "encrypt");
3028 r
= xcalloc (1, sizeof *r
+ 20 );
3029 r
->key
= pAUTHKEYTYPE
;
3030 sprintf( r
->u
.value
, "%d", algo
);
3034 if (backup_encryption_dir
)
3036 r
= xcalloc (1, sizeof *r
+ strlen (backup_encryption_dir
) );
3037 r
->key
= pBACKUPENCDIR
;
3038 strcpy (r
->u
.value
, backup_encryption_dir
);
3042 #endif /*ENABLE_CARD_SUPPORT*/
3048 algo
= ask_algo (0, &subkey_algo
, &use
);
3051 /* Create primary and subkey at once. */
3053 r
= xmalloc_clear( sizeof *r
+ 20 );
3055 sprintf( r
->u
.value
, "%d", algo
);
3058 nbits
= ask_keysize (algo
, 0);
3059 r
= xmalloc_clear( sizeof *r
+ 20 );
3060 r
->key
= pKEYLENGTH
;
3061 sprintf( r
->u
.value
, "%u", nbits
);
3064 r
= xmalloc_clear( sizeof *r
+ 20 );
3066 strcpy( r
->u
.value
, "sign" );
3070 r
= xmalloc_clear( sizeof *r
+ 20 );
3071 r
->key
= pSUBKEYTYPE
;
3072 sprintf( r
->u
.value
, "%d", subkey_algo
);
3075 r
= xmalloc_clear( sizeof *r
+ 20 );
3076 r
->key
= pSUBKEYUSAGE
;
3077 strcpy( r
->u
.value
, "encrypt" );
3083 r
= xmalloc_clear( sizeof *r
+ 20 );
3085 sprintf( r
->u
.value
, "%d", algo
);
3091 r
= xmalloc_clear( sizeof *r
+ 25 );
3093 sprintf( r
->u
.value
, "%s%s%s",
3094 (use
& PUBKEY_USAGE_SIG
)? "sign ":"",
3095 (use
& PUBKEY_USAGE_ENC
)? "encrypt ":"",
3096 (use
& PUBKEY_USAGE_AUTH
)? "auth":"" );
3103 nbits
= ask_keysize (algo
, nbits
);
3104 r
= xmalloc_clear( sizeof *r
+ 20 );
3105 r
->key
= both
? pSUBKEYLENGTH
: pKEYLENGTH
;
3106 sprintf( r
->u
.value
, "%u", nbits
);
3111 expire
= ask_expire_interval(0,NULL
);
3112 r
= xmalloc_clear( sizeof *r
+ 20 );
3113 r
->key
= pKEYEXPIRE
;
3114 r
->u
.expire
= expire
;
3117 r
= xmalloc_clear( sizeof *r
+ 20 );
3118 r
->key
= pSUBKEYEXPIRE
;
3119 r
->u
.expire
= expire
;
3123 uid
= ask_user_id(0);
3126 log_error(_("Key generation canceled.\n"));
3127 release_parameter_list( para
);
3130 r
= xmalloc_clear( sizeof *r
+ strlen(uid
) );
3132 strcpy( r
->u
.value
, uid
);
3137 dek
= card_serialno
? NULL
: do_ask_passphrase (&s2k
, 0, &canceled
);
3140 r
= xmalloc_clear( sizeof *r
);
3141 r
->key
= pPASSPHRASE_DEK
;
3145 r
= xmalloc_clear( sizeof *r
);
3146 r
->key
= pPASSPHRASE_S2K
;
3153 log_error (_("Key generation canceled.\n"));
3155 proc_parameter_file( para
, "[internal]", &outctrl
, !!card_serialno
);
3156 release_parameter_list( para
);
3160 #ifdef ENABLE_CARD_SUPPORT
3161 /* Generate a raw key and return it as a secret key packet. The
3162 function will ask for the passphrase and return a protected as well
3163 as an unprotected copy of a new secret key packet. 0 is returned
3164 on success and the caller must then free the returned values. */
3166 generate_raw_key (int algo
, unsigned int nbits
, u32 created_at
,
3167 PKT_secret_key
**r_sk_unprotected
,
3168 PKT_secret_key
**r_sk_protected
)
3172 STRING2KEY
*s2k
= NULL
;
3173 PKT_secret_key
*sk
= NULL
;
3175 size_t nskey
, npkey
;
3176 gcry_sexp_t s_parms
, s_key
;
3179 npkey
= pubkey_get_npkey (algo
);
3180 nskey
= pubkey_get_nskey (algo
);
3181 assert (nskey
<= PUBKEY_MAX_NSKEY
&& npkey
< nskey
);
3186 log_info (_("keysize invalid; using %u bits\n"), nbits
);
3191 nbits
= ((nbits
+ 31) / 32) * 32;
3192 log_info(_("keysize rounded up to %u bits\n"), nbits
);
3195 dek
= do_ask_passphrase (&s2k
, 1, &canceled
);
3198 rc
= gpg_error (GPG_ERR_CANCELED
);
3202 sk
= xmalloc_clear (sizeof *sk
);
3203 sk
->timestamp
= created_at
;
3205 sk
->pubkey_algo
= algo
;
3207 if ( !is_RSA (algo
) )
3209 log_error ("only RSA is supported for offline generated keys\n");
3210 rc
= gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
3213 rc
= gcry_sexp_build (&s_parms
, NULL
,
3214 "(genkey(rsa(nbits %d)))",
3217 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
3218 rc
= gcry_pk_genkey (&s_key
, s_parms
);
3219 gcry_sexp_release (s_parms
);
3222 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
3225 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
3226 gcry_sexp_release (s_key
);
3229 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
3233 for (i
=npkey
; i
< nskey
; i
++)
3234 sk
->csum
+= checksum_mpi (sk
->skey
[i
]);
3236 if (r_sk_unprotected
)
3237 *r_sk_unprotected
= copy_secret_key (NULL
, sk
);
3239 rc
= genhelp_protect (dek
, s2k
, sk
);
3245 *r_sk_protected
= sk
;
3251 free_secret_key (sk
);
3256 #endif /* ENABLE_CARD_SUPPORT */
3258 /* Create and delete a dummy packet to start off a list of kbnodes. */
3260 start_tree(KBNODE
*tree
)
3264 pkt
=xmalloc_clear(sizeof(*pkt
));
3265 pkt
->pkttype
=PKT_NONE
;
3266 *tree
=new_kbnode(pkt
);
3267 delete_kbnode(*tree
);
3272 do_generate_keypair (struct para_data_s
*para
,
3273 struct output_control_s
*outctrl
, int card
)
3275 KBNODE pub_root
= NULL
;
3276 KBNODE sec_root
= NULL
;
3277 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3279 struct revocation_key
*revkey
;
3284 if( outctrl
->dryrun
)
3286 log_info("dry-run mode - key generation skipped\n");
3290 if ( outctrl
->use_files
)
3292 if ( outctrl
->pub
.newfname
)
3294 iobuf_close(outctrl
->pub
.stream
);
3295 outctrl
->pub
.stream
= NULL
;
3296 if (outctrl
->pub
.fname
)
3297 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->pub
.fname
);
3298 xfree( outctrl
->pub
.fname
);
3299 outctrl
->pub
.fname
= outctrl
->pub
.newfname
;
3300 outctrl
->pub
.newfname
= NULL
;
3302 if (is_secured_filename (outctrl
->pub
.fname
) )
3304 outctrl
->pub
.stream
= NULL
;
3308 outctrl
->pub
.stream
= iobuf_create( outctrl
->pub
.fname
);
3309 if (!outctrl
->pub
.stream
)
3311 log_error(_("can't create `%s': %s\n"), outctrl
->pub
.newfname
,
3317 outctrl
->pub
.afx
->what
= 1;
3318 push_armor_filter (outctrl
->pub
.afx
, outctrl
->pub
.stream
);
3321 if (outctrl
->sec
.newfname
)
3325 iobuf_close(outctrl
->sec
.stream
);
3326 outctrl
->sec
.stream
= NULL
;
3327 if (outctrl
->sec
.fname
)
3328 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->sec
.fname
);
3329 xfree( outctrl
->sec
.fname
);
3330 outctrl
->sec
.fname
= outctrl
->sec
.newfname
;
3331 outctrl
->sec
.newfname
= NULL
;
3333 oldmask
= umask (077);
3334 if (is_secured_filename (outctrl
->sec
.fname
) )
3336 outctrl
->sec
.stream
= NULL
;
3340 outctrl
->sec
.stream
= iobuf_create( outctrl
->sec
.fname
);
3342 if (!outctrl
->sec
.stream
)
3344 log_error(_("can't create `%s': %s\n"), outctrl
->sec
.newfname
,
3350 outctrl
->sec
.afx
->what
= 5;
3351 push_armor_filter (outctrl
->sec
.afx
, outctrl
->sec
.stream
);
3354 assert( outctrl
->pub
.stream
);
3355 assert( outctrl
->sec
.stream
);
3358 log_info (_("writing public key to `%s'\n"), outctrl
->pub
.fname
);
3360 log_info (_("writing secret key stub to `%s'\n"),
3361 outctrl
->sec
.fname
);
3363 log_info(_("writing secret key to `%s'\n"), outctrl
->sec
.fname
);
3368 /* We create the packets as a tree of kbnodes. Because the
3369 structure we create is known in advance we simply generate a
3370 linked list. The first packet is a dummy packet which we flag as
3371 deleted. The very first packet must always be a KEY packet. */
3373 start_tree (&pub_root
);
3374 start_tree (&sec_root
);
3376 timestamp
= get_parameter_u32 (para
, pKEYCREATIONDATE
);
3378 timestamp
= make_timestamp ();
3382 rc
= do_create (get_parameter_algo( para
, pKEYTYPE
),
3383 get_parameter_uint( para
, pKEYLENGTH
),
3385 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3386 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3389 get_parameter_u32( para
, pKEYEXPIRE
), 0 );
3393 /* Note, that depending on the backend, the card key generation
3394 may update TIMESTAMP. */
3395 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 1, 1, pub_root
, sec_root
, NULL
,
3397 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3400 pri_sk
= sec_root
->next
->pkt
->pkt
.secret_key
;
3405 if(!rc
&& (revkey
=get_parameter_revkey(para
,pREVOKER
)))
3407 rc
= write_direct_sig (pub_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3409 rc
= write_direct_sig (sec_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3412 if( !rc
&& (s
=get_parameter_value(para
, pUSERID
)) )
3414 write_uid (pub_root
, s
);
3415 write_uid (sec_root
, s
);
3417 rc
= write_selfsigs (sec_root
, pub_root
, pri_sk
,
3418 get_parameter_uint (para
, pKEYUSAGE
), timestamp
);
3421 /* Write the auth key to the card before the encryption key. This
3422 is a partial workaround for a PGP bug (as of this writing, all
3423 versions including 8.1), that causes it to try and encrypt to
3424 the most recent subkey regardless of whether that subkey is
3425 actually an encryption type. In this case, the auth key is an
3426 RSA key so it succeeds. */
3428 if (!rc
&& card
&& get_parameter (para
, pAUTHKEYTYPE
))
3430 /* Note, that depending on the backend, the card key generation
3431 may update TIMESTAMP. */
3432 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 3, 0, pub_root
, sec_root
, NULL
,
3434 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3437 rc
= write_keybinding (pub_root
, pub_root
, pri_sk
, sub_sk
,
3438 PUBKEY_USAGE_AUTH
, timestamp
);
3440 rc
= write_keybinding (sec_root
, pub_root
, pri_sk
, sub_sk
,
3441 PUBKEY_USAGE_AUTH
, timestamp
);
3444 if( !rc
&& get_parameter( para
, pSUBKEYTYPE
) )
3448 rc
= do_create( get_parameter_algo( para
, pSUBKEYTYPE
),
3449 get_parameter_uint( para
, pSUBKEYLENGTH
),
3451 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3452 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3455 get_parameter_u32( para
, pSUBKEYEXPIRE
), 1 );
3459 if ((s
= get_parameter_value (para
, pBACKUPENCDIR
)))
3461 /* A backup of the encryption key has been requested.
3462 Generate the key in software and import it then to
3463 the card. Write a backup file. */
3464 rc
= gen_card_key_with_backup (PUBKEY_ALGO_RSA
, 2, 0,
3467 get_parameter_u32 (para
,
3473 /* Note, that depending on the backend, the card key
3474 generation may update TIMESTAMP. */
3475 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 2, 0, pub_root
, sec_root
,
3478 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3483 rc
= write_keybinding(pub_root
, pub_root
, pri_sk
, sub_sk
,
3484 get_parameter_uint (para
, pSUBKEYUSAGE
),
3487 rc
= write_keybinding(sec_root
, pub_root
, pri_sk
, sub_sk
,
3488 get_parameter_uint (para
, pSUBKEYUSAGE
),
3493 if (!rc
&& outctrl
->use_files
) /* Direct write to specified files. */
3495 rc
= write_keyblock( outctrl
->pub
.stream
, pub_root
);
3497 log_error ("can't write public key: %s\n", g10_errstr(rc
) );
3500 rc
= write_keyblock( outctrl
->sec
.stream
, sec_root
);
3502 log_error ("can't write secret key: %s\n", g10_errstr(rc
) );
3505 else if (!rc
) /* Write to the standard keyrings. */
3507 KEYDB_HANDLE pub_hd
= keydb_new (0);
3508 KEYDB_HANDLE sec_hd
= keydb_new (1);
3510 rc
= keydb_locate_writable (pub_hd
, NULL
);
3512 log_error (_("no writable public keyring found: %s\n"),
3517 rc
= keydb_locate_writable (sec_hd
, NULL
);
3519 log_error (_("no writable secret keyring found: %s\n"),
3523 if (!rc
&& opt
.verbose
)
3525 log_info (_("writing public key to `%s'\n"),
3526 keydb_get_resource_name (pub_hd
));
3528 log_info (_("writing secret key stub to `%s'\n"),
3529 keydb_get_resource_name (sec_hd
));
3531 log_info (_("writing secret key to `%s'\n"),
3532 keydb_get_resource_name (sec_hd
));
3537 rc
= keydb_insert_keyblock (pub_hd
, pub_root
);
3539 log_error (_("error writing public keyring `%s': %s\n"),
3540 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3545 rc
= keydb_insert_keyblock (sec_hd
, sec_root
);
3547 log_error (_("error writing secret keyring `%s': %s\n"),
3548 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3551 keydb_release (pub_hd
);
3552 keydb_release (sec_hd
);
3559 no_enc_rsa
= (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_RSA
3560 && get_parameter_uint (para
, pKEYUSAGE
)
3561 && !((get_parameter_uint (para
, pKEYUSAGE
)
3562 & PUBKEY_USAGE_ENC
)) );
3564 pk
= find_kbnode (pub_root
, PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3566 keyid_from_pk(pk
,pk
->main_keyid
);
3567 register_trusted_keyid(pk
->main_keyid
);
3569 update_ownertrust (pk
, ((get_ownertrust (pk
) & ~TRUST_MASK
)
3570 | TRUST_ULTIMATE
));
3574 tty_printf (_("public and secret key created and signed.\n") );
3576 list_keyblock(pub_root
,0,1,NULL
);
3581 && (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_DSA
3583 && !get_parameter (para
, pSUBKEYTYPE
) )
3585 tty_printf(_("Note that this key cannot be used for "
3586 "encryption. You may want to use\n"
3587 "the command \"--edit-key\" to generate a "
3588 "subkey for this purpose.\n") );
3596 log_error ("key generation failed: %s\n", g10_errstr(rc
) );
3598 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3599 write_status_error (card
? "card_key_generate":"key_generate", rc
);
3600 print_status_key_not_created ( get_parameter_value (para
, pHANDLE
) );
3604 PKT_public_key
*pk
= find_kbnode (pub_root
,
3605 PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3606 print_status_key_created (did_sub
? 'B':'P', pk
,
3607 get_parameter_value (para
, pHANDLE
));
3609 release_kbnode( pub_root
);
3610 release_kbnode( sec_root
);
3612 if (pri_sk
&& !card
) /* The unprotected secret key unless we */
3613 free_secret_key (pri_sk
); /* have a shallow copy in card mode. */
3615 free_secret_key(sub_sk
);
3619 /* Add a new subkey to an existing key. Returns true if a new key has
3620 been generated and put into the keyblocks. */
3622 generate_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
)
3626 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3631 char *passphrase
= NULL
;
3633 STRING2KEY
*s2k
= NULL
;
3638 /* Break out the primary secret key. */
3639 node
= find_kbnode( sec_keyblock
, PKT_SECRET_KEY
);
3642 log_error ("Oops; secret key not found anymore!\n");
3646 /* Make a copy of the sk to keep the protected one in the keyblock. */
3647 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3649 cur_time
= make_timestamp();
3651 if (pri_sk
->timestamp
> cur_time
)
3653 ulong d
= pri_sk
->timestamp
- cur_time
;
3654 log_info ( d
==1 ? _("key has been created %lu second "
3655 "in future (time warp or clock problem)\n")
3656 : _("key has been created %lu seconds "
3657 "in future (time warp or clock problem)\n"), d
);
3658 if (!opt
.ignore_time_conflict
)
3660 rc
= G10ERR_TIME_CONFLICT
;
3665 if (pri_sk
->version
< 4)
3667 log_info (_("NOTE: creating subkeys for v3 keys "
3668 "is not OpenPGP compliant\n"));
3672 if (pri_sk
->is_protected
&& pri_sk
->protect
.s2k
.mode
== 1001)
3674 tty_printf (_("Secret parts of primary key are not available.\n"));
3675 rc
= G10ERR_NO_SECKEY
;
3680 /* Unprotect to get the passphrase. */
3681 switch (is_secret_key_protected (pri_sk
) )
3684 rc
= G10ERR_PUBKEY_ALGO
;
3687 tty_printf (_("This key is not protected.\n"));
3690 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3694 tty_printf (_("Key is protected.\n"));
3695 rc
= check_secret_key ( pri_sk
, 0 );
3697 passphrase
= get_last_passphrase();
3703 algo
= ask_algo (1, NULL
, &use
);
3705 nbits
= ask_keysize (algo
, 0);
3706 expire
= ask_expire_interval (0, NULL
);
3707 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3708 _("Really create? (y/N) ")))
3713 dek
= do_ask_passphrase (&s2k
, 0, &canceled
);
3714 else if (passphrase
)
3716 s2k
= xmalloc_secure ( sizeof *s2k
);
3717 s2k
->mode
= opt
.s2k_mode
;
3718 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
3719 set_next_passphrase ( passphrase
);
3720 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
3725 rc
= GPG_ERR_CANCELED
;
3728 rc
= do_create (algo
, nbits
, pub_keyblock
, sec_keyblock
,
3729 dek
, s2k
, &sub_sk
, cur_time
, expire
, 1 );
3731 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3734 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3739 write_status_text (STATUS_KEY_CREATED
, "S");
3744 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3748 /* Release the copy of the (now unprotected) secret keys. */
3750 free_secret_key (pri_sk
);
3752 free_secret_key (sub_sk
);
3753 set_next_passphrase (NULL
);
3758 #ifdef ENABLE_CARD_SUPPORT
3759 /* Generate a subkey on a card. */
3761 generate_card_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
,
3762 int keyno
, const char *serialno
)
3766 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
;
3770 char *passphrase
= NULL
;
3772 struct para_data_s
*para
= NULL
;
3774 assert (keyno
>= 1 && keyno
<= 3);
3776 para
= xcalloc (1, sizeof *para
+ strlen (serialno
) );
3777 para
->key
= pSERIALNO
;
3778 strcpy (para
->u
.value
, serialno
);
3780 /* Break out the primary secret key */
3781 node
= find_kbnode (sec_keyblock
, PKT_SECRET_KEY
);
3784 log_error("Oops; secret key not found anymore!\n");
3788 /* Make a copy of the sk to keep the protected one in the keyblock */
3789 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3791 cur_time
= make_timestamp();
3792 if (pri_sk
->timestamp
> cur_time
)
3794 ulong d
= pri_sk
->timestamp
- cur_time
;
3795 log_info (d
==1 ? _("key has been created %lu second "
3796 "in future (time warp or clock problem)\n")
3797 : _("key has been created %lu seconds "
3798 "in future (time warp or clock problem)\n"), d
);
3799 if (!opt
.ignore_time_conflict
)
3801 rc
= G10ERR_TIME_CONFLICT
;
3806 if (pri_sk
->version
< 4)
3808 log_info (_("NOTE: creating subkeys for v3 keys "
3809 "is not OpenPGP compliant\n"));
3813 /* Unprotect to get the passphrase. */
3814 switch( is_secret_key_protected (pri_sk
) )
3817 rc
= G10ERR_PUBKEY_ALGO
;
3820 tty_printf("This key is not protected.\n");
3823 tty_printf("Key is protected.\n");
3824 rc
= check_secret_key( pri_sk
, 0 );
3826 passphrase
= get_last_passphrase();
3832 algo
= PUBKEY_ALGO_RSA
;
3833 expire
= ask_expire_interval (0,NULL
);
3835 use
= PUBKEY_USAGE_SIG
;
3836 else if (keyno
== 2)
3837 use
= PUBKEY_USAGE_ENC
;
3839 use
= PUBKEY_USAGE_AUTH
;
3840 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3841 _("Really create? (y/N) ")))
3845 set_next_passphrase (passphrase
);
3847 /* Note, that depending on the backend, the card key generation may
3849 rc
= gen_card_key (algo
, keyno
, 0, pub_keyblock
, sec_keyblock
,
3850 &sub_sk
, &cur_time
, expire
, para
);
3852 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3855 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3860 write_status_text (STATUS_KEY_CREATED
, "S");
3865 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3867 /* Release the copy of the (now unprotected) secret keys. */
3869 free_secret_key (pri_sk
);
3870 set_next_passphrase( NULL
);
3871 release_parameter_list (para
);
3874 #endif /* !ENABLE_CARD_SUPPORT */
3878 * Write a keyblock to an output stream
3881 write_keyblock( IOBUF out
, KBNODE node
)
3883 for( ; node
; node
= node
->next
)
3885 if(!is_deleted_kbnode(node
))
3887 int rc
= build_packet( out
, node
->pkt
);
3890 log_error("build_packet(%d) failed: %s\n",
3891 node
->pkt
->pkttype
, g10_errstr(rc
) );
3901 /* Note that timestamp is an in/out arg. */
3903 gen_card_key (int algo
, int keyno
, int is_primary
,
3904 KBNODE pub_root
, KBNODE sec_root
, PKT_secret_key
**ret_sk
,
3905 u32
*timestamp
, u32 expireval
, struct para_data_s
*para
)
3907 #ifdef ENABLE_CARD_SUPPORT
3910 struct agent_card_genkey_s info
;
3915 assert (algo
== PUBKEY_ALGO_RSA
);
3917 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3918 rc
= agent_scd_genkey (&info
, keyno
, 1, NULL
, *timestamp
);
3919 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3921 /* tty_printf ("\n"); */
3922 /* log_error ("WARNING: key does already exists!\n"); */
3923 /* tty_printf ("\n"); */
3924 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3925 /* _("Replace existing key? "))) */
3926 /* rc = agent_scd_genkey (&info, keyno, 1); */
3931 log_error ("key generation failed: %s\n", gpg_strerror (rc
));
3934 if ( !info
.n
|| !info
.e
)
3936 log_error ("communication error with SCD\n");
3937 gcry_mpi_release (info
.n
);
3938 gcry_mpi_release (info
.e
);
3939 return gpg_error (GPG_ERR_GENERAL
);
3942 if (*timestamp
!= info
.created_at
)
3943 log_info ("Note that the key does not use the suggested creation date\n");
3944 *timestamp
= info
.created_at
;
3946 pk
= xcalloc (1, sizeof *pk
);
3947 sk
= xcalloc (1, sizeof *sk
);
3948 sk
->timestamp
= pk
->timestamp
= info
.created_at
;
3949 sk
->version
= pk
->version
= 4;
3951 sk
->expiredate
= pk
->expiredate
= pk
->timestamp
+ expireval
;
3952 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
3953 pk
->pkey
[0] = info
.n
;
3954 pk
->pkey
[1] = info
.e
;
3955 sk
->skey
[0] = gcry_mpi_copy (pk
->pkey
[0]);
3956 sk
->skey
[1] = gcry_mpi_copy (pk
->pkey
[1]);
3957 sk
->skey
[2] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
3958 sk
->is_protected
= 1;
3959 sk
->protect
.s2k
.mode
= 1002;
3960 s
= get_parameter_value (para
, pSERIALNO
);
3963 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
3964 sk
->protect
.ivlen
++, s
+= 2)
3965 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
3971 pkt
= xcalloc (1,sizeof *pkt
);
3972 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
3973 pkt
->pkt
.public_key
= pk
;
3974 add_kbnode(pub_root
, new_kbnode( pkt
));
3976 pkt
= xcalloc (1,sizeof *pkt
);
3977 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
3978 pkt
->pkt
.secret_key
= sk
;
3979 add_kbnode(sec_root
, new_kbnode( pkt
));
3984 #endif /*!ENABLE_CARD_SUPPORT*/
3990 gen_card_key_with_backup (int algo
, int keyno
, int is_primary
,
3991 KBNODE pub_root
, KBNODE sec_root
,
3993 u32 expireval
, struct para_data_s
*para
,
3994 const char *backup_dir
)
3996 #ifdef ENABLE_CARD_SUPPORT
4000 PKT_secret_key
*sk
, *sk_unprotected
= NULL
, *sk_protected
= NULL
;
4006 /* Get the size of the key directly from the card. */
4008 struct agent_card_info_s info
;
4010 memset (&info
, 0, sizeof info
);
4011 if (!agent_scd_getattr ("KEY-ATTR", &info
)
4012 && info
.key_attr
[1].algo
)
4013 nbits
= info
.key_attr
[1].nbits
;
4015 nbits
= 1024; /* All pre-v2.0 cards. */
4016 agent_release_card_info (&info
);
4019 /* Create a key of this size in memory. */
4020 rc
= generate_raw_key (algo
, nbits
, timestamp
,
4021 &sk_unprotected
, &sk_protected
);
4025 /* Store the key to the card. */
4026 rc
= save_unprotected_key_to_card (sk_unprotected
, keyno
);
4029 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc
));
4030 free_secret_key (sk_unprotected
);
4031 free_secret_key (sk_protected
);
4032 write_status_error ("save_key_to_card", rc
);
4036 /* Get rid of the secret key parameters and store the serial numer. */
4037 sk
= sk_unprotected
;
4038 n
= pubkey_get_nskey (sk
->pubkey_algo
);
4039 for (i
=pubkey_get_npkey (sk
->pubkey_algo
); i
< n
; i
++)
4041 gcry_mpi_release (sk
->skey
[i
]);
4044 i
= pubkey_get_npkey (sk
->pubkey_algo
);
4045 sk
->skey
[i
] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
4046 sk
->is_protected
= 1;
4047 sk
->protect
.s2k
.mode
= 1002;
4048 s
= get_parameter_value (para
, pSERIALNO
);
4050 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
4051 sk
->protect
.ivlen
++, s
+= 2)
4052 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
4054 /* Now write the *protected* secret key to the file. */
4056 char name_buffer
[50];
4061 keyid_from_sk (sk
, NULL
);
4062 snprintf (name_buffer
, sizeof name_buffer
, "sk_%08lX%08lX.gpg",
4063 (ulong
)sk
->keyid
[0], (ulong
)sk
->keyid
[1]);
4065 fname
= make_filename (backup_dir
, name_buffer
, NULL
);
4066 oldmask
= umask (077);
4067 if (is_secured_filename (fname
))
4073 fp
= iobuf_create (fname
);
4077 rc
= gpg_error_from_syserror ();
4078 log_error (_("can't create backup file `%s': %s\n"),
4079 fname
, strerror(errno
) );
4081 free_secret_key (sk_unprotected
);
4082 free_secret_key (sk_protected
);
4086 pkt
= xcalloc (1, sizeof *pkt
);
4087 pkt
->pkttype
= PKT_SECRET_KEY
;
4088 pkt
->pkt
.secret_key
= sk_protected
;
4089 sk_protected
= NULL
;
4091 rc
= build_packet (fp
, pkt
);
4094 log_error("build packet failed: %s\n", g10_errstr(rc
) );
4099 unsigned char array
[MAX_FINGERPRINT_LEN
];
4103 iobuf_ioctl (NULL
, 2, 0, (char*)fname
);
4104 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname
);
4106 fingerprint_from_sk (sk
, array
, &n
);
4107 p
= fprbuf
= xmalloc (MAX_FINGERPRINT_LEN
*2 + 1 + 1);
4108 for (i
=0; i
< n
; i
++, p
+= 2)
4109 sprintf (p
, "%02X", array
[i
]);
4113 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED
,
4115 fname
, strlen (fname
),
4124 free_secret_key (sk_unprotected
);
4129 /* Create the public key from the secret key. */
4130 pk
= xcalloc (1, sizeof *pk
);
4131 pk
->timestamp
= sk
->timestamp
;
4132 pk
->version
= sk
->version
;
4134 pk
->expiredate
= sk
->expiredate
= sk
->timestamp
+ expireval
;
4135 pk
->pubkey_algo
= sk
->pubkey_algo
;
4136 n
= pubkey_get_npkey (sk
->pubkey_algo
);
4137 for (i
=0; i
< n
; i
++)
4138 pk
->pkey
[i
] = mpi_copy (sk
->skey
[i
]);
4140 /* Build packets and add them to the node lists. */
4141 pkt
= xcalloc (1,sizeof *pkt
);
4142 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
4143 pkt
->pkt
.public_key
= pk
;
4144 add_kbnode(pub_root
, new_kbnode( pkt
));
4146 pkt
= xcalloc (1,sizeof *pkt
);
4147 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
4148 pkt
->pkt
.secret_key
= sk
;
4149 add_kbnode(sec_root
, new_kbnode( pkt
));
4154 #endif /*!ENABLE_CARD_SUPPORT*/
4158 #ifdef ENABLE_CARD_SUPPORT
4160 save_unprotected_key_to_card (PKT_secret_key
*sk
, int keyno
)
4163 unsigned char *rsa_n
= NULL
;
4164 unsigned char *rsa_e
= NULL
;
4165 unsigned char *rsa_p
= NULL
;
4166 unsigned char *rsa_q
= NULL
;
4167 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
4168 unsigned char *sexp
= NULL
;
4170 char numbuf
[55], numbuf2
[50];
4172 assert (is_RSA (sk
->pubkey_algo
));
4173 assert (!sk
->is_protected
);
4175 /* Copy the parameters into straight buffers. */
4176 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_n
, &rsa_n_len
, sk
->skey
[0]);
4177 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_e
, &rsa_e_len
, sk
->skey
[1]);
4178 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_p
, &rsa_p_len
, sk
->skey
[3]);
4179 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_q
, &rsa_q_len
, sk
->skey
[4]);
4180 if (!rsa_n
|| !rsa_e
|| !rsa_p
|| !rsa_q
)
4182 rc
= G10ERR_INV_ARG
;
4186 /* Put the key into an S-expression. */
4187 sexp
= p
= xmalloc_secure (30
4188 + rsa_n_len
+ rsa_e_len
+ rsa_p_len
+ rsa_q_len
4189 + 4*sizeof (numbuf
) + 25 + sizeof(numbuf
) + 20);
4191 p
= stpcpy (p
,"(11:private-key(3:rsa(1:n");
4192 sprintf (numbuf
, "%u:", (unsigned int)rsa_n_len
);
4193 p
= stpcpy (p
, numbuf
);
4194 memcpy (p
, rsa_n
, rsa_n_len
);
4197 sprintf (numbuf
, ")(1:e%u:", (unsigned int)rsa_e_len
);
4198 p
= stpcpy (p
, numbuf
);
4199 memcpy (p
, rsa_e
, rsa_e_len
);
4202 sprintf (numbuf
, ")(1:p%u:", (unsigned int)rsa_p_len
);
4203 p
= stpcpy (p
, numbuf
);
4204 memcpy (p
, rsa_p
, rsa_p_len
);
4207 sprintf (numbuf
, ")(1:q%u:", (unsigned int)rsa_q_len
);
4208 p
= stpcpy (p
, numbuf
);
4209 memcpy (p
, rsa_q
, rsa_q_len
);
4212 p
= stpcpy (p
,"))(10:created-at");
4213 sprintf (numbuf2
, "%lu", (unsigned long)sk
->timestamp
);
4214 sprintf (numbuf
, "%lu:", (unsigned long)strlen (numbuf2
));
4215 p
= stpcpy (stpcpy (stpcpy (p
, numbuf
), numbuf2
), "))");
4217 /* Fixme: Unfortunately we don't have the serialnumber available -
4218 thus we can't pass it down to the agent. */
4219 rc
= agent_scd_writekey (keyno
, NULL
, sexp
, p
- sexp
);
4229 #endif /*ENABLE_CARD_SUPPORT*/