1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2009 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
[20*4+1]; /* Enough for 20 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 /* The default hash algo order is:
350 SHA-256, SHA-1, SHA-384, SHA-512, SHA-224.
351 Ordering SHA-1 before SHA-384 might be viewed as a bit
352 strange; it is done because we expect that soon enough
353 SHA-3 will be available and at that point there should
354 be no more need for SHA-384 etc. Anyway this order is
355 just a default and can easily be changed by a config
357 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256
))
358 strcat (dummy_string
, "H8 ");
360 strcat (dummy_string
, "H2 "); /* SHA-1 */
362 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384
))
363 strcat (dummy_string
, "H9 ");
365 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512
))
366 strcat (dummy_string
, "H10 ");
368 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224
))
369 strcat (dummy_string
, "H11 ");
373 strcat(dummy_string
,"Z2 ");
375 if(!check_compress_algo(COMPRESS_ALGO_BZIP2
))
376 strcat(dummy_string
,"Z3 ");
379 strcat(dummy_string
,"Z1");
384 else if (!ascii_strcasecmp (string
, "none"))
389 char *tok
,*prefstring
;
391 prefstring
=xstrdup(string
); /* need a writable string! */
393 while((tok
=strsep(&prefstring
," ,")))
395 if((val
=string_to_cipher_algo (tok
)))
397 if(set_one_pref(val
,1,tok
,sym
,&nsym
))
400 else if((val
=string_to_digest_algo (tok
)))
402 if(set_one_pref(val
,2,tok
,hash
,&nhash
))
405 else if((val
=string_to_compress_algo(tok
))>-1)
407 if(set_one_pref(val
,3,tok
,zip
,&nzip
))
410 else if (ascii_strcasecmp(tok
,"mdc")==0)
412 else if (ascii_strcasecmp(tok
,"no-mdc")==0)
414 else if (ascii_strcasecmp(tok
,"ks-modify")==0)
416 else if (ascii_strcasecmp(tok
,"no-ks-modify")==0)
420 log_info (_("invalid item `%s' in preference string\n"),tok
);
422 /* Complain if IDEA is not available. */
423 if(ascii_strcasecmp(tok
,"s1")==0
424 || ascii_strcasecmp(tok
,"idea")==0)
438 if(personal
==PREFTYPE_SYM
)
440 xfree(opt
.personal_cipher_prefs
);
443 opt
.personal_cipher_prefs
=NULL
;
448 opt
.personal_cipher_prefs
=
449 xmalloc(sizeof(prefitem_t
*)*(nsym
+1));
451 for (i
=0; i
<nsym
; i
++)
453 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_SYM
;
454 opt
.personal_cipher_prefs
[i
].value
= sym
[i
];
457 opt
.personal_cipher_prefs
[i
].type
= PREFTYPE_NONE
;
458 opt
.personal_cipher_prefs
[i
].value
= 0;
461 else if(personal
==PREFTYPE_HASH
)
463 xfree(opt
.personal_digest_prefs
);
466 opt
.personal_digest_prefs
=NULL
;
471 opt
.personal_digest_prefs
=
472 xmalloc(sizeof(prefitem_t
*)*(nhash
+1));
474 for (i
=0; i
<nhash
; i
++)
476 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_HASH
;
477 opt
.personal_digest_prefs
[i
].value
= hash
[i
];
480 opt
.personal_digest_prefs
[i
].type
= PREFTYPE_NONE
;
481 opt
.personal_digest_prefs
[i
].value
= 0;
484 else if(personal
==PREFTYPE_ZIP
)
486 xfree(opt
.personal_compress_prefs
);
489 opt
.personal_compress_prefs
=NULL
;
494 opt
.personal_compress_prefs
=
495 xmalloc(sizeof(prefitem_t
*)*(nzip
+1));
497 for (i
=0; i
<nzip
; i
++)
499 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_ZIP
;
500 opt
.personal_compress_prefs
[i
].value
= zip
[i
];
503 opt
.personal_compress_prefs
[i
].type
= PREFTYPE_NONE
;
504 opt
.personal_compress_prefs
[i
].value
= 0;
510 memcpy (sym_prefs
, sym
, (nsym_prefs
=nsym
));
511 memcpy (hash_prefs
, hash
, (nhash_prefs
=nhash
));
512 memcpy (zip_prefs
, zip
, (nzip_prefs
=nzip
));
515 prefs_initialized
= 1;
522 /* Return a fake user ID containing the preferences. Caller must
525 keygen_get_std_prefs(void)
528 PKT_user_id
*uid
=xmalloc_clear(sizeof(PKT_user_id
));
530 if(!prefs_initialized
)
531 keygen_set_std_prefs(NULL
,0);
535 uid
->prefs
=xmalloc((sizeof(prefitem_t
*)*
536 (nsym_prefs
+nhash_prefs
+nzip_prefs
+1)));
538 for(i
=0;i
<nsym_prefs
;i
++,j
++)
540 uid
->prefs
[j
].type
=PREFTYPE_SYM
;
541 uid
->prefs
[j
].value
=sym_prefs
[i
];
544 for(i
=0;i
<nhash_prefs
;i
++,j
++)
546 uid
->prefs
[j
].type
=PREFTYPE_HASH
;
547 uid
->prefs
[j
].value
=hash_prefs
[i
];
550 for(i
=0;i
<nzip_prefs
;i
++,j
++)
552 uid
->prefs
[j
].type
=PREFTYPE_ZIP
;
553 uid
->prefs
[j
].value
=zip_prefs
[i
];
556 uid
->prefs
[j
].type
=PREFTYPE_NONE
;
557 uid
->prefs
[j
].value
=0;
559 uid
->flags
.mdc
=mdc_available
;
560 uid
->flags
.ks_modify
=ks_modify
;
566 add_feature_mdc (PKT_signature
*sig
,int enabled
)
573 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
, &n
);
574 /* Already set or cleared */
576 ((enabled
&& (s
[0] & 0x01)) || (!enabled
&& !(s
[0] & 0x01))))
579 if (!s
|| !n
) { /* create a new one */
581 buf
= xmalloc_clear (n
);
589 buf
[0] |= 0x01; /* MDC feature */
593 /* Are there any bits set? */
599 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_FEATURES
);
601 build_sig_subpkt (sig
, SIGSUBPKT_FEATURES
, buf
, n
);
607 add_keyserver_modify (PKT_signature
*sig
,int enabled
)
614 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
617 s
= parse_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
, &n
);
618 /* Already set or cleared */
620 ((enabled
&& (s
[0] & 0x80)) || (!enabled
&& !(s
[0] & 0x80))))
623 if (!s
|| !n
) { /* create a new one */
625 buf
= xmalloc_clear (n
);
633 buf
[0] |= 0x80; /* no-modify flag */
637 /* Are there any bits set? */
643 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_KS_FLAGS
);
645 build_sig_subpkt (sig
, SIGSUBPKT_KS_FLAGS
, buf
, n
);
652 keygen_upd_std_prefs (PKT_signature
*sig
, void *opaque
)
656 if (!prefs_initialized
)
657 keygen_set_std_prefs (NULL
, 0);
660 build_sig_subpkt (sig
, SIGSUBPKT_PREF_SYM
, sym_prefs
, nsym_prefs
);
663 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_SYM
);
664 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_SYM
);
668 build_sig_subpkt (sig
, SIGSUBPKT_PREF_HASH
, hash_prefs
, nhash_prefs
);
671 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_HASH
);
672 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_HASH
);
676 build_sig_subpkt (sig
, SIGSUBPKT_PREF_COMPR
, zip_prefs
, nzip_prefs
);
679 delete_sig_subpkt (sig
->hashed
, SIGSUBPKT_PREF_COMPR
);
680 delete_sig_subpkt (sig
->unhashed
, SIGSUBPKT_PREF_COMPR
);
683 /* Make sure that the MDC feature flag is set if needed. */
684 add_feature_mdc (sig
,mdc_available
);
685 add_keyserver_modify (sig
,ks_modify
);
686 keygen_add_keyserver_url(sig
,NULL
);
693 * Add preference to the self signature packet.
694 * This is only called for packets with version > 3.
698 keygen_add_std_prefs( PKT_signature
*sig
, void *opaque
)
700 PKT_public_key
*pk
= opaque
;
702 do_add_key_flags (sig
, pk
->pubkey_usage
);
703 keygen_add_key_expire( sig
, opaque
);
704 keygen_upd_std_prefs (sig
, opaque
);
705 keygen_add_keyserver_url(sig
,NULL
);
711 keygen_add_keyserver_url(PKT_signature
*sig
, void *opaque
)
713 const char *url
=opaque
;
716 url
=opt
.def_keyserver_url
;
719 build_sig_subpkt(sig
,SIGSUBPKT_PREF_KS
,url
,strlen(url
));
721 delete_sig_subpkt (sig
->hashed
,SIGSUBPKT_PREF_KS
);
727 keygen_add_notations(PKT_signature
*sig
,void *opaque
)
729 struct notation
*notation
;
731 /* We always start clean */
732 delete_sig_subpkt(sig
->hashed
,SIGSUBPKT_NOTATION
);
733 delete_sig_subpkt(sig
->unhashed
,SIGSUBPKT_NOTATION
);
734 sig
->flags
.notation
=0;
736 for(notation
=opaque
;notation
;notation
=notation
->next
)
737 if(!notation
->flags
.ignore
)
742 n1
=strlen(notation
->name
);
743 if(notation
->altvalue
)
744 n2
=strlen(notation
->altvalue
);
745 else if(notation
->bdat
)
748 n2
=strlen(notation
->value
);
750 buf
= xmalloc( 8 + n1
+ n2
);
752 /* human readable or not */
753 buf
[0] = notation
->bdat
?0:0x80;
754 buf
[1] = buf
[2] = buf
[3] = 0;
759 memcpy(buf
+8, notation
->name
, n1
);
760 if(notation
->altvalue
)
761 memcpy(buf
+8+n1
, notation
->altvalue
, n2
);
762 else if(notation
->bdat
)
763 memcpy(buf
+8+n1
, notation
->bdat
, n2
);
765 memcpy(buf
+8+n1
, notation
->value
, n2
);
766 build_sig_subpkt( sig
, SIGSUBPKT_NOTATION
|
767 (notation
->flags
.critical
?SIGSUBPKT_FLAG_CRITICAL
:0),
776 keygen_add_revkey(PKT_signature
*sig
, void *opaque
)
778 struct revocation_key
*revkey
=opaque
;
779 byte buf
[2+MAX_FINGERPRINT_LEN
];
781 buf
[0]=revkey
->class;
782 buf
[1]=revkey
->algid
;
783 memcpy(&buf
[2],revkey
->fpr
,MAX_FINGERPRINT_LEN
);
785 build_sig_subpkt(sig
,SIGSUBPKT_REV_KEY
,buf
,2+MAX_FINGERPRINT_LEN
);
787 /* All sigs with revocation keys set are nonrevocable */
788 sig
->flags
.revocable
=0;
790 build_sig_subpkt( sig
, SIGSUBPKT_REVOCABLE
, buf
, 1 );
799 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
800 signature creation time. */
802 make_backsig (PKT_signature
*sig
,PKT_public_key
*pk
,
803 PKT_public_key
*sub_pk
,PKT_secret_key
*sub_sk
,
806 PKT_signature
*backsig
;
809 cache_public_key(sub_pk
);
811 rc
= make_keysig_packet (&backsig
, pk
, NULL
, sub_pk
, sub_sk
, 0x19,
812 0, 0, timestamp
, 0, NULL
, NULL
);
814 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc
));
817 /* Get it into a binary packed form. */
818 IOBUF backsig_out
=iobuf_temp();
821 init_packet(&backsig_pkt
);
822 backsig_pkt
.pkttype
=PKT_SIGNATURE
;
823 backsig_pkt
.pkt
.signature
=backsig
;
824 rc
=build_packet(backsig_out
,&backsig_pkt
);
825 free_packet(&backsig_pkt
);
827 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc
));
831 byte
*buf
=iobuf_get_temp_buffer(backsig_out
);
833 /* Remove the packet header */
843 pktlen
=(buf
[1]-192)*256;
849 pktlen
=buf
[2] << 24;
850 pktlen
|=buf
[3] << 16;
869 pktlen
=buf
[mark
++] << 24;
870 pktlen
|=buf
[mark
++] << 16;
873 pktlen
|=buf
[mark
++] << 8;
882 /* Now make the binary blob into a subpacket. */
883 build_sig_subpkt(sig
,SIGSUBPKT_SIGNATURE
,buf
,pktlen
);
885 iobuf_close(backsig_out
);
894 write_direct_sig (KBNODE root
, KBNODE pub_root
, PKT_secret_key
*sk
,
895 struct revocation_key
*revkey
, u32 timestamp
)
904 log_info(_("writing direct signature\n"));
906 /* Get the pk packet from the pub_tree. */
907 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
910 pk
= node
->pkt
->pkt
.public_key
;
912 /* We have to cache the key, so that the verification of the
913 signature creation is able to retrieve the public key. */
914 cache_public_key (pk
);
916 /* Make the signature. */
917 rc
= make_keysig_packet (&sig
,pk
,NULL
,NULL
,sk
,0x1F,
919 keygen_add_revkey
, revkey
);
922 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
926 pkt
= xmalloc_clear( sizeof *pkt
);
927 pkt
->pkttype
= PKT_SIGNATURE
;
928 pkt
->pkt
.signature
= sig
;
929 add_kbnode( root
, new_kbnode( pkt
) );
935 write_selfsigs( KBNODE sec_root
, KBNODE pub_root
, PKT_secret_key
*sk
,
936 unsigned int use
, u32 timestamp
)
946 log_info(_("writing self signature\n"));
948 /* Get the uid packet from the list. */
949 node
= find_kbnode( pub_root
, PKT_USER_ID
);
951 BUG(); /* No user id packet in tree. */
952 uid
= node
->pkt
->pkt
.user_id
;
954 /* Get the pk packet from the pub_tree. */
955 node
= find_kbnode( pub_root
, PKT_PUBLIC_KEY
);
958 pk
= node
->pkt
->pkt
.public_key
;
959 pk
->pubkey_usage
= use
;
961 /* We have to cache the key, so that the verification of the
962 signature creation is able to retrieve the public key. */
963 cache_public_key (pk
);
965 /* Make the signature. */
966 rc
= make_keysig_packet (&sig
, pk
, uid
, NULL
, sk
, 0x13,
968 keygen_add_std_prefs
, pk
);
971 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
975 pkt
= xmalloc_clear( sizeof *pkt
);
976 pkt
->pkttype
= PKT_SIGNATURE
;
977 pkt
->pkt
.signature
= sig
;
978 add_kbnode( sec_root
, new_kbnode( pkt
) );
980 pkt
= xmalloc_clear( sizeof *pkt
);
981 pkt
->pkttype
= PKT_SIGNATURE
;
982 pkt
->pkt
.signature
= copy_signature(NULL
,sig
);
983 add_kbnode( pub_root
, new_kbnode( pkt
) );
988 /* Write the key binding signature. If TIMESTAMP is not NULL use the
989 signature creation times. */
991 write_keybinding (KBNODE root
, KBNODE pub_root
,
992 PKT_secret_key
*pri_sk
, PKT_secret_key
*sub_sk
,
993 unsigned int use
, u32 timestamp
)
999 PKT_public_key
*pri_pk
, *sub_pk
;
1000 struct opaque_data_usage_and_pk oduap
;
1003 log_info(_("writing key binding signature\n"));
1005 /* Get the pk packet from the pub_tree. */
1006 node
= find_kbnode ( pub_root
, PKT_PUBLIC_KEY
);
1009 pri_pk
= node
->pkt
->pkt
.public_key
;
1011 /* We have to cache the key, so that the verification of the
1012 * signature creation is able to retrieve the public key. */
1013 cache_public_key (pri_pk
);
1015 /* Find the last subkey. */
1017 for (node
=pub_root
; node
; node
= node
->next
)
1019 if ( node
->pkt
->pkttype
== PKT_PUBLIC_SUBKEY
)
1020 sub_pk
= node
->pkt
->pkt
.public_key
;
1025 /* Make the signature. */
1028 rc
= make_keysig_packet (&sig
, pri_pk
, NULL
, sub_pk
, pri_sk
, 0x18,
1030 keygen_add_key_flags_and_expire
, &oduap
);
1033 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc
) );
1037 /* Make a backsig. */
1038 if (use
&PUBKEY_USAGE_SIG
)
1040 rc
= make_backsig (sig
, pri_pk
, sub_pk
, sub_sk
, timestamp
);
1045 pkt
= xmalloc_clear ( sizeof *pkt
);
1046 pkt
->pkttype
= PKT_SIGNATURE
;
1047 pkt
->pkt
.signature
= sig
;
1048 add_kbnode (root
, new_kbnode (pkt
) );
1055 key_from_sexp (gcry_mpi_t
*array
, gcry_sexp_t sexp
,
1056 const char *topname
, const char *elems
)
1058 gcry_sexp_t list
, l2
;
1063 list
= gcry_sexp_find_token (sexp
, topname
, 0);
1065 return gpg_error (GPG_ERR_INV_OBJ
);
1066 l2
= gcry_sexp_cadr (list
);
1067 gcry_sexp_release (list
);
1070 return gpg_error (GPG_ERR_NO_OBJ
);
1072 for (idx
=0,s
=elems
; *s
; s
++, idx
++)
1074 l2
= gcry_sexp_find_token (list
, s
, 1);
1077 rc
= gpg_error (GPG_ERR_NO_OBJ
); /* required parameter not found */
1080 array
[idx
] = gcry_sexp_nth_mpi (l2
, 1, GCRYMPI_FMT_USG
);
1081 gcry_sexp_release (l2
);
1084 rc
= gpg_error (GPG_ERR_INV_OBJ
); /* required parameter invalid */
1088 gcry_sexp_release (list
);
1093 for (i
=0; i
<idx
; i
++)
1098 gcry_sexp_release (list
);
1105 genhelp_protect (DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
*sk
)
1111 sk
->protect
.algo
= dek
->algo
;
1112 sk
->protect
.s2k
= *s2k
;
1113 rc
= protect_secret_key (sk
, dek
);
1115 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc
) );
1122 genhelp_factors (gcry_sexp_t misc_key_info
, KBNODE sec_root
)
1124 (void)misc_key_info
;
1126 #if 0 /* Not used anymore */
1132 /* DSA: don't know whether it makes sense to have the factors, so for now
1133 we store them in the secret keyring (but they are not secret)
1134 p = 2 * q * f1 * f2 * ... * fn
1135 We store only f1 to f_n-1; fn can be calculated because p and q
1137 n
= gcry_sexp_sprint (misc_key_info
, 0, NULL
, 0);
1138 buf
= xmalloc (n
+4);
1139 strcpy (buf
, "#::");
1140 n
= gcry_sexp_sprint (misc_key_info
, 0, buf
+3, n
);
1144 add_kbnode (sec_root
, make_comment_node_from_buffer (buf
, n
));
1147 gcry_sexp_release (misc_key_info
);
1153 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1154 time to be put into the key structure. */
1156 gen_elg (int algo
, unsigned int nbits
,
1157 KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1158 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1159 u32 timestamp
, u32 expireval
, int is_subkey
)
1165 gcry_sexp_t s_parms
, s_key
;
1166 gcry_sexp_t misc_key_info
;
1168 assert( is_ELGAMAL(algo
) );
1173 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1178 nbits
= ((nbits
+ 31) / 32) * 32;
1179 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1183 rc
= gcry_sexp_build ( &s_parms
, NULL
,
1184 "(genkey(%s(nbits %d)))",
1185 algo
== GCRY_PK_ELG_E
? "openpgp-elg" :
1186 algo
== GCRY_PK_ELG
? "elg" : "x-oops" ,
1189 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1191 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1192 gcry_sexp_release (s_parms
);
1195 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1199 sk
= xmalloc_clear( sizeof *sk
);
1200 pk
= xmalloc_clear( sizeof *pk
);
1201 sk
->timestamp
= pk
->timestamp
= timestamp
;
1202 sk
->version
= pk
->version
= 4;
1205 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1207 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1209 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pgy");
1212 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1213 gcry_sexp_release (s_key
);
1214 free_secret_key (sk
);
1215 free_public_key (pk
);
1218 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pgyx");
1221 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1222 gcry_sexp_release (s_key
);
1223 free_secret_key (sk
);
1224 free_public_key (pk
);
1227 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1228 gcry_sexp_release (s_key
);
1230 sk
->is_protected
= 0;
1231 sk
->protect
.algo
= 0;
1233 sk
->csum
= checksum_mpi (sk
->skey
[3]);
1234 if (ret_sk
) /* Return an unprotected version of the sk. */
1235 *ret_sk
= copy_secret_key ( NULL
, sk
);
1237 rc
= genhelp_protect (dek
, s2k
, sk
);
1240 free_public_key (pk
);
1241 free_secret_key (sk
);
1242 gcry_sexp_release (misc_key_info
);
1246 pkt
= xmalloc_clear (sizeof *pkt
);
1247 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1248 pkt
->pkt
.public_key
= pk
;
1249 add_kbnode (pub_root
, new_kbnode( pkt
));
1251 /* Don't know whether it makes sense to have access to the factors,
1252 so for now we store them in the secret keyring (but they are not
1254 pkt
= xmalloc_clear (sizeof *pkt
);
1255 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1256 pkt
->pkt
.secret_key
= sk
;
1257 add_kbnode (sec_root
, new_kbnode( pkt
));
1259 genhelp_factors (misc_key_info
, sec_root
);
1266 * Generate a DSA key
1269 gen_dsa (unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1270 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1271 u32 timestamp
, u32 expireval
, int is_subkey
)
1277 gcry_sexp_t s_parms
, s_key
;
1278 gcry_sexp_t misc_key_info
;
1284 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1286 else if ( nbits
> 3072 )
1289 log_info(_("keysize invalid; using %u bits\n"), nbits
);
1294 nbits
= ((nbits
+ 63) / 64) * 64;
1295 log_info(_("keysize rounded up to %u bits\n"), nbits
);
1298 /* To comply with FIPS rules we round up to the next value unless in
1300 if (!opt
.expert
&& nbits
> 1024 && (nbits
% 1024))
1302 nbits
= ((nbits
+ 1023) / 1024) * 1024;
1303 log_info(_("keysize rounded up to %u bits\n"), nbits
);
1307 Figure out a q size based on the key size. FIPS 180-3 says:
1314 2048/256 is an odd pair since there is also a 2048/224 and
1315 3072/256. Matching sizes is not a very exact science.
1317 We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1318 but less than 2048, and 160 for 1024 (DSA1).
1323 else if ( nbits
> 1024)
1329 log_info (_("WARNING: some OpenPGP programs can't"
1330 " handle a DSA key with this digest size\n"));
1332 rc
= gcry_sexp_build (&s_parms
, NULL
,
1333 "(genkey(dsa(nbits %d)(qbits %d)))",
1334 (int)nbits
, (int)qbits
);
1336 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1338 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1339 gcry_sexp_release (s_parms
);
1342 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1346 sk
= xmalloc_clear( sizeof *sk
);
1347 pk
= xmalloc_clear( sizeof *pk
);
1348 sk
->timestamp
= pk
->timestamp
= timestamp
;
1349 sk
->version
= pk
->version
= 4;
1351 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1352 sk
->pubkey_algo
= pk
->pubkey_algo
= PUBKEY_ALGO_DSA
;
1354 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "pqgy");
1357 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1358 gcry_sexp_release (s_key
);
1359 free_public_key(pk
);
1360 free_secret_key(sk
);
1363 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "pqgyx");
1366 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1367 gcry_sexp_release (s_key
);
1368 free_public_key(pk
);
1369 free_secret_key(sk
);
1372 misc_key_info
= gcry_sexp_find_token (s_key
, "misc-key-info", 0);
1373 gcry_sexp_release (s_key
);
1375 sk
->is_protected
= 0;
1376 sk
->protect
.algo
= 0;
1378 sk
->csum
= checksum_mpi ( sk
->skey
[4] );
1379 if( ret_sk
) /* return an unprotected version of the sk */
1380 *ret_sk
= copy_secret_key( NULL
, sk
);
1382 rc
= genhelp_protect (dek
, s2k
, sk
);
1385 free_public_key (pk
);
1386 free_secret_key (sk
);
1387 gcry_sexp_release (misc_key_info
);
1391 pkt
= xmalloc_clear(sizeof *pkt
);
1392 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1393 pkt
->pkt
.public_key
= pk
;
1394 add_kbnode(pub_root
, new_kbnode( pkt
));
1396 /* Don't know whether it makes sense to have the factors, so for now
1397 * we store them in the secret keyring (but they are not secret)
1398 * p = 2 * q * f1 * f2 * ... * fn
1399 * We store only f1 to f_n-1; fn can be calculated because p and q
1402 pkt
= xmalloc_clear(sizeof *pkt
);
1403 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1404 pkt
->pkt
.secret_key
= sk
;
1405 add_kbnode(sec_root
, new_kbnode( pkt
));
1407 genhelp_factors (misc_key_info
, sec_root
);
1414 * Generate an RSA key.
1417 gen_rsa (int algo
, unsigned nbits
, KBNODE pub_root
, KBNODE sec_root
, DEK
*dek
,
1418 STRING2KEY
*s2k
, PKT_secret_key
**ret_sk
,
1419 u32 timestamp
, u32 expireval
, int is_subkey
)
1425 gcry_sexp_t s_parms
, s_key
;
1427 assert (is_RSA(algo
));
1432 log_info (_("keysize invalid; using %u bits\n"), nbits
);
1437 nbits
= ((nbits
+ 31) / 32) * 32;
1438 log_info (_("keysize rounded up to %u bits\n"), nbits
);
1441 rc
= gcry_sexp_build (&s_parms
, NULL
,
1442 "(genkey(rsa(nbits %d)))",
1445 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
1447 rc
= gcry_pk_genkey (&s_key
, s_parms
);
1448 gcry_sexp_release (s_parms
);
1451 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
1455 sk
= xmalloc_clear( sizeof *sk
);
1456 pk
= xmalloc_clear( sizeof *pk
);
1457 sk
->timestamp
= pk
->timestamp
= timestamp
;
1458 sk
->version
= pk
->version
= 4;
1461 sk
->expiredate
= pk
->expiredate
= sk
->timestamp
+ expireval
;
1463 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
1465 rc
= key_from_sexp (pk
->pkey
, s_key
, "public-key", "ne");
1468 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
));
1469 gcry_sexp_release (s_key
);
1470 free_public_key(pk
);
1471 free_secret_key(sk
);
1474 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
1477 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
1478 gcry_sexp_release (s_key
);
1479 free_public_key(pk
);
1480 free_secret_key(sk
);
1483 gcry_sexp_release (s_key
);
1485 sk
->is_protected
= 0;
1486 sk
->protect
.algo
= 0;
1488 sk
->csum
= checksum_mpi (sk
->skey
[2] );
1489 sk
->csum
+= checksum_mpi (sk
->skey
[3] );
1490 sk
->csum
+= checksum_mpi (sk
->skey
[4] );
1491 sk
->csum
+= checksum_mpi (sk
->skey
[5] );
1492 if( ret_sk
) /* return an unprotected version of the sk */
1493 *ret_sk
= copy_secret_key( NULL
, sk
);
1495 rc
= genhelp_protect (dek
, s2k
, sk
);
1498 free_public_key (pk
);
1499 free_secret_key (sk
);
1503 pkt
= xmalloc_clear(sizeof *pkt
);
1504 pkt
->pkttype
= is_subkey
? PKT_PUBLIC_SUBKEY
: PKT_PUBLIC_KEY
;
1505 pkt
->pkt
.public_key
= pk
;
1506 add_kbnode(pub_root
, new_kbnode( pkt
));
1508 pkt
= xmalloc_clear(sizeof *pkt
);
1509 pkt
->pkttype
= is_subkey
? PKT_SECRET_SUBKEY
: PKT_SECRET_KEY
;
1510 pkt
->pkt
.secret_key
= sk
;
1511 add_kbnode(sec_root
, new_kbnode( pkt
));
1519 * return 0 on error or the multiplier
1522 check_valid_days( const char *s
)
1532 return 0; /* e.g. "2323wc" */
1533 if( *s
== 'd' || *s
== 'D' )
1535 if( *s
== 'w' || *s
== 'W' )
1537 if( *s
== 'm' || *s
== 'M' )
1539 if( *s
== 'y' || *s
== 'Y' )
1546 print_key_flags(int flags
)
1548 if(flags
&PUBKEY_USAGE_SIG
)
1549 tty_printf("%s ",_("Sign"));
1551 if(flags
&PUBKEY_USAGE_CERT
)
1552 tty_printf("%s ",_("Certify"));
1554 if(flags
&PUBKEY_USAGE_ENC
)
1555 tty_printf("%s ",_("Encrypt"));
1557 if(flags
&PUBKEY_USAGE_AUTH
)
1558 tty_printf("%s ",_("Authenticate"));
1562 /* Returns the key flags */
1564 ask_key_flags(int algo
,int subkey
)
1566 /* TRANSLATORS: Please use only plain ASCII characters for the
1567 translation. If this is not possible use single digits. The
1568 string needs to 8 bytes long. Here is a description of the
1571 s = Toggle signing capability
1572 e = Toggle encryption capability
1573 a = Toggle authentication capability
1576 const char *togglers
=_("SsEeAaQq");
1578 unsigned int current
=0;
1579 unsigned int possible
=openpgp_pk_algo_usage(algo
);
1581 if ( strlen(togglers
) != 8 )
1583 tty_printf ("NOTE: Bad translation at %s:%d. "
1584 "Please report.\n", __FILE__
, __LINE__
);
1585 togglers
= "11223300";
1588 /* Only primary keys may certify. */
1590 possible
&=~PUBKEY_USAGE_CERT
;
1592 /* Preload the current set with the possible set, minus
1593 authentication, since nobody really uses auth yet. */
1594 current
=possible
&~PUBKEY_USAGE_AUTH
;
1599 tty_printf(_("Possible actions for a %s key: "),
1600 gcry_pk_algo_name (algo
));
1601 print_key_flags(possible
);
1603 tty_printf(_("Current allowed actions: "));
1604 print_key_flags(current
);
1607 if(possible
&PUBKEY_USAGE_SIG
)
1608 tty_printf(_(" (%c) Toggle the sign capability\n"),
1610 if(possible
&PUBKEY_USAGE_ENC
)
1611 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1613 if(possible
&PUBKEY_USAGE_AUTH
)
1614 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1617 tty_printf(_(" (%c) Finished\n"),togglers
[6]);
1621 answer
= cpr_get("keygen.flags",_("Your selection? "));
1624 if(strlen(answer
)>1)
1625 tty_printf(_("Invalid selection.\n"));
1626 else if(*answer
=='\0' || *answer
==togglers
[6] || *answer
==togglers
[7])
1628 else if((*answer
==togglers
[0] || *answer
==togglers
[1])
1629 && possible
&PUBKEY_USAGE_SIG
)
1631 if(current
&PUBKEY_USAGE_SIG
)
1632 current
&=~PUBKEY_USAGE_SIG
;
1634 current
|=PUBKEY_USAGE_SIG
;
1636 else if((*answer
==togglers
[2] || *answer
==togglers
[3])
1637 && possible
&PUBKEY_USAGE_ENC
)
1639 if(current
&PUBKEY_USAGE_ENC
)
1640 current
&=~PUBKEY_USAGE_ENC
;
1642 current
|=PUBKEY_USAGE_ENC
;
1644 else if((*answer
==togglers
[4] || *answer
==togglers
[5])
1645 && possible
&PUBKEY_USAGE_AUTH
)
1647 if(current
&PUBKEY_USAGE_AUTH
)
1648 current
&=~PUBKEY_USAGE_AUTH
;
1650 current
|=PUBKEY_USAGE_AUTH
;
1653 tty_printf(_("Invalid selection.\n"));
1662 /* Ask for an algorithm. The function returns the algorithm id to
1663 * create. If ADDMODE is false the function won't show an option to
1664 * create the primary and subkey combined and won't set R_USAGE
1665 * either. If a combined algorithm has been selected, the subkey
1666 * algorithm is stored at R_SUBKEY_ALGO. */
1668 ask_algo (int addmode
, int *r_subkey_algo
, unsigned int *r_usage
)
1675 r_subkey_algo
= &dummy_algo
;
1677 tty_printf (_("Please select what kind of key you want:\n"));
1680 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1682 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1684 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1685 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1689 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1690 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1694 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1695 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1702 answer
= cpr_get ("keygen.algo", _("Your selection? "));
1704 algo
= *answer
? atoi (answer
) : 1;
1706 if (algo
== 1 && !addmode
)
1708 algo
= PUBKEY_ALGO_RSA
;
1709 *r_subkey_algo
= PUBKEY_ALGO_RSA
;
1712 else if (algo
== 2 && !addmode
)
1714 algo
= PUBKEY_ALGO_DSA
;
1715 *r_subkey_algo
= PUBKEY_ALGO_ELGAMAL_E
;
1720 algo
= PUBKEY_ALGO_DSA
;
1721 *r_usage
= PUBKEY_USAGE_SIG
;
1726 algo
= PUBKEY_ALGO_RSA
;
1727 *r_usage
= PUBKEY_USAGE_SIG
;
1730 else if (algo
== 5 && addmode
)
1732 algo
= PUBKEY_ALGO_ELGAMAL_E
;
1733 *r_usage
= PUBKEY_USAGE_ENC
;
1736 else if (algo
== 6 && addmode
)
1738 algo
= PUBKEY_ALGO_RSA
;
1739 *r_usage
= PUBKEY_USAGE_ENC
;
1742 else if (algo
== 7 && opt
.expert
)
1744 algo
= PUBKEY_ALGO_DSA
;
1745 *r_usage
= ask_key_flags (algo
, addmode
);
1748 else if (algo
== 8 && opt
.expert
)
1750 algo
= PUBKEY_ALGO_RSA
;
1751 *r_usage
= ask_key_flags (algo
, addmode
);
1755 tty_printf (_("Invalid selection.\n"));
1762 /* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
1763 is not 0, the function asks for the size of the encryption
1766 ask_keysize (int algo
, unsigned int primary_keysize
)
1768 unsigned int nbits
, min
, def
=2048, max
=4096;
1769 int for_subkey
= !!primary_keysize
;
1777 if (primary_keysize
&& !opt
.expert
)
1779 /* Deduce the subkey size from the primary key size. */
1780 if (algo
== PUBKEY_ALGO_DSA
&& primary_keysize
> 3072)
1781 nbits
= 3072; /* For performance reasons we don't support more
1782 than 3072 bit DSA. However we won't see this
1783 case anyway because DSA can't be used as an
1784 encryption subkey ;-). */
1786 nbits
= primary_keysize
;
1793 case PUBKEY_ALGO_DSA
:
1798 case PUBKEY_ALGO_RSA
:
1803 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1804 gcry_pk_algo_name (algo
), min
, max
);
1808 char *prompt
, *answer
;
1811 prompt
= xasprintf (_("What keysize do you want "
1812 "for the subkey? (%u) "), def
);
1814 prompt
= xasprintf (_("What keysize do you want? (%u) "), def
);
1815 answer
= cpr_get ("keygen.size", prompt
);
1817 nbits
= *answer
? atoi (answer
): def
;
1821 if(nbits
<min
|| nbits
>max
)
1822 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1823 gcry_pk_algo_name (algo
), min
, max
);
1828 tty_printf(_("Requested keysize is %u bits\n"), nbits
);
1831 if( algo
== PUBKEY_ALGO_DSA
&& (nbits
% 64) )
1833 nbits
= ((nbits
+ 63) / 64) * 64;
1835 tty_printf(_("rounded up to %u bits\n"), nbits
);
1837 else if( (nbits
% 32) )
1839 nbits
= ((nbits
+ 31) / 32) * 32;
1841 tty_printf(_("rounded up to %u bits\n"), nbits
);
1849 * Parse an expire string and return its value in seconds.
1850 * Returns (u32)-1 on error.
1851 * This isn't perfect since scan_isodatestr returns unix time, and
1852 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1853 * Because of this, we only permit setting expirations up to 2106, but
1854 * OpenPGP could theoretically allow up to 2242. I think we'll all
1855 * just cope for the next few years until we get a 64-bit time_t or
1859 parse_expire_string( const char *string
)
1864 u32 curtime
= make_timestamp ();
1869 else if (!strncmp (string
, "seconds=", 8))
1870 seconds
= atoi (string
+8);
1871 else if ((abs_date
= scan_isodatestr(string
))
1872 && (abs_date
+86400/2) > curtime
)
1873 seconds
= (abs_date
+86400/2) - curtime
;
1874 else if ((tt
= isotime2epoch (string
)) != (time_t)(-1))
1875 seconds
= (u32
)tt
- curtime
;
1876 else if ((mult
= check_valid_days (string
)))
1877 seconds
= atoi (string
) * 86400L * mult
;
1879 seconds
= (u32
)(-1);
1884 /* Parsean Creation-Date string which is either "1986-04-26" or
1885 "19860426T042640". Returns 0 on error. */
1887 parse_creation_string (const char *string
)
1893 else if ( !strncmp (string
, "seconds=", 8) )
1894 seconds
= atoi (string
+8);
1895 else if ( !(seconds
= scan_isodatestr (string
)))
1897 time_t tmp
= isotime2epoch (string
);
1898 seconds
= (tmp
== (time_t)(-1))? 0 : tmp
;
1904 /* object == 0 for a key, and 1 for a sig */
1906 ask_expire_interval(int object
,const char *def_expire
)
1916 tty_printf(_("Please specify how long the key should be valid.\n"
1917 " 0 = key does not expire\n"
1918 " <n> = key expires in n days\n"
1919 " <n>w = key expires in n weeks\n"
1920 " <n>m = key expires in n months\n"
1921 " <n>y = key expires in n years\n"));
1927 tty_printf(_("Please specify how long the signature should be valid.\n"
1928 " 0 = signature does not expire\n"
1929 " <n> = signature expires in n days\n"
1930 " <n>w = signature expires in n weeks\n"
1931 " <n>m = signature expires in n months\n"
1932 " <n>y = signature expires in n years\n"));
1939 /* Note: The elgamal subkey for DSA has no expiration date because
1940 * it must be signed with the DSA key and this one has the expiration
1946 u32 curtime
=make_timestamp();
1950 answer
= cpr_get("keygen.valid",_("Key is valid for? (0) "));
1955 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1956 /* This will actually end up larger than necessary because
1957 of the 2 bytes for '%s' */
1958 prompt
=xmalloc(strlen(PROMPTSTRING
)+strlen(def_expire
)+1);
1959 sprintf(prompt
,PROMPTSTRING
,def_expire
);
1962 answer
= cpr_get("siggen.valid",prompt
);
1966 answer
=xstrdup(def_expire
);
1969 trim_spaces(answer
);
1970 interval
= parse_expire_string( answer
);
1971 if( interval
== (u32
)-1 )
1973 tty_printf(_("invalid value\n"));
1979 tty_printf((object
==0)
1980 ? _("Key does not expire at all\n")
1981 : _("Signature does not expire at all\n"));
1985 tty_printf(object
==0
1986 ? _("Key expires at %s\n")
1987 : _("Signature expires at %s\n"),
1988 asctimestamp((ulong
)(curtime
+ interval
) ) );
1989 #if SIZEOF_TIME_T <= 4
1990 if ( (time_t)((ulong
)(curtime
+interval
)) < 0 )
1991 tty_printf (_("Your system can't display dates beyond 2038.\n"
1992 "However, it will be correctly handled up to"
1995 #endif /*SIZEOF_TIME_T*/
1996 if ( (time_t)((unsigned long)(curtime
+interval
)) < curtime
)
1998 tty_printf (_("invalid value\n"));
2003 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2004 _("Is this correct? (y/N) ")) )
2015 u32 x
= ask_expire_interval(0,NULL
);
2016 return x
? make_timestamp() + x
: 0;
2021 static PKT_user_id
*
2022 uid_from_string (const char *string
)
2027 n
= strlen (string
);
2028 uid
= xmalloc_clear (sizeof *uid
+ n
);
2030 strcpy (uid
->name
, string
);
2036 /* Ask for a user ID. With a MODE of 1 an extra help prompt is
2037 printed for use during a new key creation. If KEYBLOCK is not NULL
2038 the function prevents the creation of an already existing user
2041 ask_user_id (int mode
, KBNODE keyblock
)
2044 char *aname
, *acomment
, *amail
, *uid
;
2048 /* TRANSLATORS: This is the new string telling the user what
2049 gpg is now going to do (i.e. ask for the parts of the user
2050 ID). Note that if you do not tyranslated this string, a
2051 different string will be used used, which might still have
2052 a correct transaltion. */
2055 "GnuPG needs to construct a user ID to identify your key.\n"
2057 const char *s2
= _(s1
);
2059 if (!strcmp (s1
, s2
))
2061 /* There is no translation for the string thus we to use
2062 the old info text. gettext has no way to tell whether
2063 a translation is actually available, thus we need to
2064 to compare again. */
2065 /* TRANSLATORS: This string is in general not anymore used
2066 but you should keep your existing translation. In case
2067 the new string is not translated this old string will
2069 const char *s3
= N_("\n"
2070 "You need a user ID to identify your key; "
2071 "the software constructs the user ID\n"
2072 "from the Real Name, Comment and Email Address in this form:\n"
2073 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2074 const char *s4
= _(s3
);
2075 if (strcmp (s3
, s4
))
2076 s2
= s3
; /* A translation exists - use it. */
2078 tty_printf ("%s", s2
) ;
2080 uid
= aname
= acomment
= amail
= NULL
;
2088 aname
= cpr_get("keygen.name",_("Real name: "));
2092 if( opt
.allow_freeform_uid
)
2095 if( strpbrk( aname
, "<>" ) )
2096 tty_printf(_("Invalid character in name\n"));
2097 else if( digitp(aname
) )
2098 tty_printf(_("Name may not start with a digit\n"));
2099 else if( strlen(aname
) < 5 )
2100 tty_printf(_("Name must be at least 5 characters long\n"));
2108 amail
= cpr_get("keygen.email",_("Email address: "));
2111 if( !*amail
|| opt
.allow_freeform_uid
)
2112 break; /* no email address is okay */
2113 else if ( !is_valid_mailbox (amail
) )
2114 tty_printf(_("Not a valid email address\n"));
2122 acomment
= cpr_get("keygen.comment",_("Comment: "));
2123 trim_spaces(acomment
);
2126 break; /* no comment is okay */
2127 else if( strpbrk( acomment
, "()" ) )
2128 tty_printf(_("Invalid character in comment\n"));
2136 uid
= p
= xmalloc(strlen(aname
)+strlen(amail
)+strlen(acomment
)+12+10);
2137 p
= stpcpy(p
, aname
);
2139 p
= stpcpy(stpcpy(stpcpy(p
," ("), acomment
),")");
2141 p
= stpcpy(stpcpy(stpcpy(p
," <"), amail
),">");
2143 /* Append a warning if the RNG is switched into fake mode. */
2144 if ( random_is_faked () )
2145 strcpy(p
, " (insecure!)" );
2147 /* print a note in case that UTF8 mapping has to be done */
2148 for(p
=uid
; *p
; p
++ ) {
2150 tty_printf(_("You are using the `%s' character set.\n"),
2151 get_native_charset() );
2156 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid
);
2158 if( !*amail
&& !opt
.allow_freeform_uid
2159 && (strchr( aname
, '@' ) || strchr( acomment
, '@'))) {
2161 tty_printf(_("Please don't put the email address "
2162 "into the real name or the comment\n") );
2165 if (!fail
&& keyblock
)
2167 PKT_user_id
*uidpkt
= uid_from_string (uid
);
2170 for (node
=keyblock
; node
&& !fail
; node
=node
->next
)
2171 if (!is_deleted_kbnode (node
)
2172 && node
->pkt
->pkttype
== PKT_USER_ID
2173 && !cmp_user_ids (uidpkt
, node
->pkt
->pkt
.user_id
))
2176 tty_printf (_("Such a user ID already exists on this key!\n"));
2177 free_user_id (uidpkt
);
2181 /* TRANSLATORS: These are the allowed answers in
2182 lower and uppercase. Below you will find the matching
2183 string which should be translated accordingly and the
2184 letter changed to match the one in the answer string.
2189 o = Okay (ready, continue)
2192 const char *ansstr
= _("NnCcEeOoQq");
2194 if( strlen(ansstr
) != 10 )
2196 if( cpr_enabled() ) {
2197 answer
= xstrdup(ansstr
+6);
2201 answer
= cpr_get("keygen.userid.cmd", fail
?
2202 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2203 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2206 if( strlen(answer
) > 1 )
2208 else if( *answer
== ansstr
[0] || *answer
== ansstr
[1] ) {
2209 xfree(aname
); aname
= NULL
;
2212 else if( *answer
== ansstr
[2] || *answer
== ansstr
[3] ) {
2213 xfree(acomment
); acomment
= NULL
;
2216 else if( *answer
== ansstr
[4] || *answer
== ansstr
[5] ) {
2217 xfree(amail
); amail
= NULL
;
2220 else if( *answer
== ansstr
[6] || *answer
== ansstr
[7] ) {
2222 tty_printf(_("Please correct the error first\n"));
2225 xfree(aname
); aname
= NULL
;
2226 xfree(acomment
); acomment
= NULL
;
2227 xfree(amail
); amail
= NULL
;
2231 else if( *answer
== ansstr
[8] || *answer
== ansstr
[9] ) {
2232 xfree(aname
); aname
= NULL
;
2233 xfree(acomment
); acomment
= NULL
;
2234 xfree(amail
); amail
= NULL
;
2235 xfree(uid
); uid
= NULL
;
2241 if( !amail
&& !acomment
&& !amail
)
2243 xfree(uid
); uid
= NULL
;
2246 char *p
= native_to_utf8( uid
);
2254 /* MODE 0 - standard
2255 1 - Ask for passphrase of the card backup key. */
2257 do_ask_passphrase (STRING2KEY
**ret_s2k
, int mode
, int *r_canceled
)
2261 const char *errtext
= NULL
;
2262 const char *custdesc
= NULL
;
2264 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2267 custdesc
= _("Please enter a passphrase to protect the off-card "
2268 "backup of the new encryption key.");
2270 s2k
= xmalloc_secure( sizeof *s2k
);
2272 s2k
->mode
= opt
.s2k_mode
;
2273 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2274 dek
= passphrase_to_dek_ext (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2275 errtext
, custdesc
, NULL
, r_canceled
);
2276 if (!dek
&& *r_canceled
) {
2277 xfree(dek
); dek
= NULL
;
2278 xfree(s2k
); s2k
= NULL
;
2282 errtext
= N_("passphrase not correctly repeated; try again");
2283 tty_printf(_("%s.\n"), _(errtext
));
2285 else if( !dek
->keylen
) {
2286 xfree(dek
); dek
= NULL
;
2287 xfree(s2k
); s2k
= NULL
;
2289 "You don't want a passphrase - this is probably a *bad* idea!\n"
2290 "I will do it anyway. You can change your passphrase at any time,\n"
2291 "using this program with the option \"--edit-key\".\n\n"));
2302 /* Basic key generation. Here we divert to the actual generation
2303 routines based on the requested algorithm. */
2305 do_create (int algo
, unsigned int nbits
, KBNODE pub_root
, KBNODE sec_root
,
2306 DEK
*dek
, STRING2KEY
*s2k
, PKT_secret_key
**sk
,
2307 u32 timestamp
, u32 expiredate
, int is_subkey
)
2313 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2314 "some other action (type on the keyboard, move the mouse, utilize the\n"
2315 "disks) during the prime generation; this gives the random number\n"
2316 "generator a better chance to gain enough entropy.\n") );
2318 if( algo
== PUBKEY_ALGO_ELGAMAL_E
)
2319 rc
= gen_elg(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2320 timestamp
, expiredate
, is_subkey
);
2321 else if( algo
== PUBKEY_ALGO_DSA
)
2322 rc
= gen_dsa(nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2323 timestamp
, expiredate
, is_subkey
);
2324 else if( algo
== PUBKEY_ALGO_RSA
)
2325 rc
= gen_rsa(algo
, nbits
, pub_root
, sec_root
, dek
, s2k
, sk
,
2326 timestamp
, expiredate
, is_subkey
);
2334 /* Generate a new user id packet or return NULL if canceled. If
2335 KEYBLOCK is not NULL the function prevents the creation of an
2336 already existing user ID. */
2338 generate_user_id (KBNODE keyblock
)
2342 p
= ask_user_id (1, keyblock
);
2344 return NULL
; /* Canceled. */
2345 return uid_from_string (p
);
2350 release_parameter_list( struct para_data_s
*r
)
2352 struct para_data_s
*r2
;
2354 for( ; r
; r
= r2
) {
2356 if( r
->key
== pPASSPHRASE_DEK
)
2358 else if( r
->key
== pPASSPHRASE_S2K
)
2365 static struct para_data_s
*
2366 get_parameter( struct para_data_s
*para
, enum para_name key
)
2368 struct para_data_s
*r
;
2370 for( r
= para
; r
&& r
->key
!= key
; r
= r
->next
)
2376 get_parameter_value( struct para_data_s
*para
, enum para_name key
)
2378 struct para_data_s
*r
= get_parameter( para
, key
);
2379 return (r
&& *r
->u
.value
)? r
->u
.value
: NULL
;
2383 get_parameter_algo( struct para_data_s
*para
, enum para_name key
)
2386 struct para_data_s
*r
= get_parameter( para
, key
);
2389 if( digitp( r
->u
.value
) )
2390 i
= atoi( r
->u
.value
);
2391 else if ( !strcmp ( r
->u
.value
, "ELG-E")
2392 || !strcmp ( r
->u
.value
, "ELG") )
2395 i
= gcry_pk_map_name (r
->u
.value
);
2396 if (i
== PUBKEY_ALGO_RSA_E
|| i
== PUBKEY_ALGO_RSA_S
)
2397 i
= 0; /* we don't want to allow generation of these algorithms */
2402 * Parse the usage parameter and set the keyflags. Returns -1 on
2403 * error, 0 for no usage given or 1 for usage available.
2406 parse_parameter_usage (const char *fname
,
2407 struct para_data_s
*para
, enum para_name key
)
2409 struct para_data_s
*r
= get_parameter( para
, key
);
2414 return 0; /* none (this is an optional parameter)*/
2418 while ( (p
= strsep (&pn
, " \t,")) ) {
2421 else if ( !ascii_strcasecmp (p
, "sign") )
2422 use
|= PUBKEY_USAGE_SIG
;
2423 else if ( !ascii_strcasecmp (p
, "encrypt") )
2424 use
|= PUBKEY_USAGE_ENC
;
2425 else if ( !ascii_strcasecmp (p
, "auth") )
2426 use
|= PUBKEY_USAGE_AUTH
;
2428 log_error("%s:%d: invalid usage list\n", fname
, r
->lnr
);
2429 return -1; /* error */
2437 parse_revocation_key (const char *fname
,
2438 struct para_data_s
*para
, enum para_name key
)
2440 struct para_data_s
*r
= get_parameter( para
, key
);
2441 struct revocation_key revkey
;
2446 return 0; /* none (this is an optional parameter) */
2451 revkey
.algid
=atoi(pn
);
2455 /* Skip to the fpr */
2456 while(*pn
&& *pn
!=':')
2464 for(i
=0;i
<MAX_FINGERPRINT_LEN
&& *pn
;i
++,pn
+=2)
2466 int c
=hextobyte(pn
);
2473 /* skip to the tag */
2474 while(*pn
&& *pn
!='s' && *pn
!='S')
2477 if(ascii_strcasecmp(pn
,"sensitive")==0)
2480 memcpy(&r
->u
.revkey
,&revkey
,sizeof(struct revocation_key
));
2485 log_error("%s:%d: invalid revocation key\n", fname
, r
->lnr
);
2486 return -1; /* error */
2491 get_parameter_u32( struct para_data_s
*para
, enum para_name key
)
2493 struct para_data_s
*r
= get_parameter( para
, key
);
2497 if( r
->key
== pKEYCREATIONDATE
)
2498 return r
->u
.creation
;
2499 if( r
->key
== pKEYEXPIRE
|| r
->key
== pSUBKEYEXPIRE
)
2501 if( r
->key
== pKEYUSAGE
|| r
->key
== pSUBKEYUSAGE
)
2504 return (unsigned int)strtoul( r
->u
.value
, NULL
, 10 );
2508 get_parameter_uint( struct para_data_s
*para
, enum para_name key
)
2510 return get_parameter_u32( para
, key
);
2514 get_parameter_dek( struct para_data_s
*para
, enum para_name key
)
2516 struct para_data_s
*r
= get_parameter( para
, key
);
2517 return r
? r
->u
.dek
: NULL
;
2521 get_parameter_s2k( struct para_data_s
*para
, enum para_name key
)
2523 struct para_data_s
*r
= get_parameter( para
, key
);
2524 return r
? r
->u
.s2k
: NULL
;
2527 static struct revocation_key
*
2528 get_parameter_revkey( struct para_data_s
*para
, enum para_name key
)
2530 struct para_data_s
*r
= get_parameter( para
, key
);
2531 return r
? &r
->u
.revkey
: NULL
;
2535 proc_parameter_file( struct para_data_s
*para
, const char *fname
,
2536 struct output_control_s
*outctrl
, int card
)
2538 struct para_data_s
*r
;
2539 const char *s1
, *s2
, *s3
;
2542 int have_user_id
=0,err
,algo
;
2544 /* Check that we have all required parameters. */
2545 r
= get_parameter( para
, pKEYTYPE
);
2548 algo
=get_parameter_algo(para
,pKEYTYPE
);
2549 if (openpgp_pk_test_algo2 (algo
, PUBKEY_USAGE_SIG
))
2551 log_error ("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2557 log_error ("%s: no Key-Type specified\n",fname
);
2561 err
= parse_parameter_usage (fname
, para
, pKEYUSAGE
);
2564 /* Default to algo capabilities if key-usage is not provided */
2565 r
= xmalloc_clear(sizeof(*r
));
2567 r
->u
.usage
= openpgp_pk_algo_usage(algo
);
2575 r
= get_parameter (para
, pKEYUSAGE
);
2576 if (r
&& (r
->u
.usage
& ~openpgp_pk_algo_usage (algo
)))
2578 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2579 fname
, r
->lnr
, algo
);
2584 r
= get_parameter( para
, pSUBKEYTYPE
);
2587 algo
= get_parameter_algo (para
, pSUBKEYTYPE
);
2588 if (openpgp_pk_test_algo (algo
))
2590 log_error ("%s:%d: invalid algorithm\n", fname
, r
->lnr
);
2594 err
= parse_parameter_usage (fname
, para
, pSUBKEYUSAGE
);
2597 /* Default to algo capabilities if subkey-usage is not
2599 r
= xmalloc_clear (sizeof(*r
));
2600 r
->key
= pSUBKEYUSAGE
;
2601 r
->u
.usage
= openpgp_pk_algo_usage (algo
);
2609 r
= get_parameter (para
, pSUBKEYUSAGE
);
2610 if (r
&& (r
->u
.usage
& ~openpgp_pk_algo_usage (algo
)))
2612 log_error ("%s:%d: specified Subkey-Usage not allowed"
2613 " for algo %d\n", fname
, r
->lnr
, algo
);
2620 if( get_parameter_value( para
, pUSERID
) )
2624 /* create the formatted user ID */
2625 s1
= get_parameter_value( para
, pNAMEREAL
);
2626 s2
= get_parameter_value( para
, pNAMECOMMENT
);
2627 s3
= get_parameter_value( para
, pNAMEEMAIL
);
2628 if( s1
|| s2
|| s3
)
2630 n
= (s1
?strlen(s1
):0) + (s2
?strlen(s2
):0) + (s3
?strlen(s3
):0);
2631 r
= xmalloc_clear( sizeof *r
+ n
+ 20 );
2637 p
= stpcpy(stpcpy(stpcpy(p
," ("), s2
),")");
2639 p
= stpcpy(stpcpy(stpcpy(p
," <"), s3
),">");
2648 log_error("%s: no User-ID specified\n",fname
);
2652 /* Set preferences, if any. */
2653 keygen_set_std_prefs(get_parameter_value( para
, pPREFERENCES
), 0);
2655 /* Set keyserver, if any. */
2656 s1
=get_parameter_value( para
, pKEYSERVER
);
2659 struct keyserver_spec
*spec
;
2661 spec
=parse_keyserver_uri(s1
,1,NULL
,0);
2664 free_keyserver_spec(spec
);
2665 opt
.def_keyserver_url
=s1
;
2669 log_error("%s:%d: invalid keyserver url\n", fname
, r
->lnr
);
2674 /* Set revoker, if any. */
2675 if (parse_revocation_key (fname
, para
, pREVOKER
))
2678 /* Make DEK and S2K from the Passphrase. */
2679 if (outctrl
->ask_passphrase
)
2681 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2682 feature is required so that GUIs are able to do a key
2683 creation but have gpg-agent ask for the passphrase. */
2688 dek
= do_ask_passphrase (&s2k
, 0, &canceled
);
2691 r
= xmalloc_clear( sizeof *r
);
2692 r
->key
= pPASSPHRASE_DEK
;
2696 r
= xmalloc_clear( sizeof *r
);
2697 r
->key
= pPASSPHRASE_S2K
;
2705 log_error ("%s:%d: key generation canceled\n", fname
, r
->lnr
);
2711 r
= get_parameter( para
, pPASSPHRASE
);
2712 if ( r
&& *r
->u
.value
)
2714 /* We have a plain text passphrase - create a DEK from it.
2715 * It is a little bit ridiculous to keep it in secure memory
2716 * but because we do this always, why not here. */
2720 s2k
= xmalloc_secure ( sizeof *s2k
);
2721 s2k
->mode
= opt
.s2k_mode
;
2722 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
2723 set_next_passphrase ( r
->u
.value
);
2724 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
2726 set_next_passphrase (NULL
);
2728 memset (r
->u
.value
, 0, strlen(r
->u
.value
));
2730 r
= xmalloc_clear (sizeof *r
);
2731 r
->key
= pPASSPHRASE_S2K
;
2735 r
= xmalloc_clear (sizeof *r
);
2736 r
->key
= pPASSPHRASE_DEK
;
2743 /* Make KEYCREATIONDATE from Creation-Date. */
2744 r
= get_parameter (para
, pCREATIONDATE
);
2745 if (r
&& *r
->u
.value
)
2749 seconds
= parse_creation_string (r
->u
.value
);
2752 log_error ("%s:%d: invalid creation date\n", fname
, r
->lnr
);
2755 r
->u
.creation
= seconds
;
2756 r
->key
= pKEYCREATIONDATE
; /* Change that entry. */
2759 /* Make KEYEXPIRE from Expire-Date. */
2760 r
= get_parameter( para
, pEXPIREDATE
);
2761 if( r
&& *r
->u
.value
)
2765 seconds
= parse_expire_string( r
->u
.value
);
2766 if( seconds
== (u32
)-1 )
2768 log_error("%s:%d: invalid expire date\n", fname
, r
->lnr
);
2771 r
->u
.expire
= seconds
;
2772 r
->key
= pKEYEXPIRE
; /* change hat entry */
2773 /* also set it for the subkey */
2774 r
= xmalloc_clear( sizeof *r
+ 20 );
2775 r
->key
= pSUBKEYEXPIRE
;
2776 r
->u
.expire
= seconds
;
2781 if( !!outctrl
->pub
.newfname
^ !!outctrl
->sec
.newfname
) {
2782 log_error("%s:%d: only one ring name is set\n", fname
, outctrl
->lnr
);
2786 do_generate_keypair( para
, outctrl
, card
);
2792 * Kludge to allow non interactive key generation controlled
2793 * by a parameter file.
2794 * Note, that string parameters are expected to be in UTF-8
2797 read_parameter_file( const char *fname
)
2799 static struct { const char *name
;
2802 { "Key-Type", pKEYTYPE
},
2803 { "Key-Length", pKEYLENGTH
},
2804 { "Key-Usage", pKEYUSAGE
},
2805 { "Subkey-Type", pSUBKEYTYPE
},
2806 { "Subkey-Length", pSUBKEYLENGTH
},
2807 { "Subkey-Usage", pSUBKEYUSAGE
},
2808 { "Name-Real", pNAMEREAL
},
2809 { "Name-Email", pNAMEEMAIL
},
2810 { "Name-Comment", pNAMECOMMENT
},
2811 { "Expire-Date", pEXPIREDATE
},
2812 { "Creation-Date", pCREATIONDATE
},
2813 { "Passphrase", pPASSPHRASE
},
2814 { "Preferences", pPREFERENCES
},
2815 { "Revoker", pREVOKER
},
2816 { "Handle", pHANDLE
},
2817 { "Keyserver", pKEYSERVER
},
2822 unsigned int maxlen
, nline
;
2825 const char *err
= NULL
;
2826 struct para_data_s
*para
, *r
;
2828 struct output_control_s outctrl
;
2830 memset( &outctrl
, 0, sizeof( outctrl
) );
2831 outctrl
.pub
.afx
= new_armor_context ();
2832 outctrl
.sec
.afx
= new_armor_context ();
2834 if( !fname
|| !*fname
)
2837 fp
= iobuf_open (fname
);
2838 if (fp
&& is_secured_file (iobuf_get_fd (fp
)))
2845 log_error (_("can't open `%s': %s\n"), fname
, strerror(errno
) );
2848 iobuf_ioctl (fp
, 3, 1, NULL
); /* No file caching. */
2855 while ( iobuf_read_line (fp
, &line
, &nline
, &maxlen
) ) {
2856 char *keyword
, *value
;
2860 err
= "line too long";
2863 for( p
= line
; isspace(*(byte
*)p
); p
++ )
2865 if( !*p
|| *p
== '#' )
2868 if( *keyword
== '%' ) {
2869 for( ; !isspace(*(byte
*)p
); p
++ )
2873 for( ; isspace(*(byte
*)p
); p
++ )
2876 trim_trailing_ws( value
, strlen(value
) );
2877 if( !ascii_strcasecmp( keyword
, "%echo" ) )
2878 log_info("%s\n", value
);
2879 else if( !ascii_strcasecmp( keyword
, "%dry-run" ) )
2881 else if( !ascii_strcasecmp( keyword
, "%ask-passphrase" ) )
2882 outctrl
.ask_passphrase
= 1;
2883 else if( !ascii_strcasecmp( keyword
, "%no-ask-passphrase" ) )
2884 outctrl
.ask_passphrase
= 0;
2885 else if( !ascii_strcasecmp( keyword
, "%commit" ) ) {
2887 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2888 print_status_key_not_created
2889 (get_parameter_value (para
, pHANDLE
));
2890 release_parameter_list( para
);
2893 else if( !ascii_strcasecmp( keyword
, "%pubring" ) ) {
2894 if( outctrl
.pub
.fname
&& !strcmp( outctrl
.pub
.fname
, value
) )
2895 ; /* still the same file - ignore it */
2897 xfree( outctrl
.pub
.newfname
);
2898 outctrl
.pub
.newfname
= xstrdup( value
);
2899 outctrl
.use_files
= 1;
2902 else if( !ascii_strcasecmp( keyword
, "%secring" ) ) {
2903 if( outctrl
.sec
.fname
&& !strcmp( outctrl
.sec
.fname
, value
) )
2904 ; /* still the same file - ignore it */
2906 xfree( outctrl
.sec
.newfname
);
2907 outctrl
.sec
.newfname
= xstrdup( value
);
2908 outctrl
.use_files
= 1;
2912 log_info("skipping control `%s' (%s)\n", keyword
, value
);
2919 if( !(p
= strchr( p
, ':' )) || p
== keyword
) {
2920 err
= "missing colon";
2925 for( ; isspace(*(byte
*)p
); p
++ )
2928 err
= "missing argument";
2932 trim_trailing_ws( value
, strlen(value
) );
2934 for(i
=0; keywords
[i
].name
; i
++ ) {
2935 if( !ascii_strcasecmp( keywords
[i
].name
, keyword
) )
2938 if( !keywords
[i
].name
) {
2939 err
= "unknown keyword";
2942 if( keywords
[i
].key
!= pKEYTYPE
&& !para
) {
2943 err
= "parameter block does not start with \"Key-Type\"";
2947 if( keywords
[i
].key
== pKEYTYPE
&& para
) {
2949 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2950 print_status_key_not_created
2951 (get_parameter_value (para
, pHANDLE
));
2952 release_parameter_list( para
);
2956 for( r
= para
; r
; r
= r
->next
) {
2957 if( r
->key
== keywords
[i
].key
)
2961 err
= "duplicate keyword";
2965 r
= xmalloc_clear( sizeof *r
+ strlen( value
) );
2967 r
->key
= keywords
[i
].key
;
2968 strcpy( r
->u
.value
, value
);
2973 log_error("%s:%d: %s\n", fname
, lnr
, err
);
2974 else if( iobuf_error (fp
) ) {
2975 log_error("%s:%d: read error\n", fname
, lnr
);
2979 if (proc_parameter_file( para
, fname
, &outctrl
, 0 ))
2980 print_status_key_not_created (get_parameter_value (para
, pHANDLE
));
2983 if( outctrl
.use_files
) { /* close open streams */
2984 iobuf_close( outctrl
.pub
.stream
);
2985 iobuf_close( outctrl
.sec
.stream
);
2987 /* Must invalidate that ugly cache to actually close it. */
2988 if (outctrl
.pub
.fname
)
2989 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.pub
.fname
);
2990 if (outctrl
.sec
.fname
)
2991 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
.sec
.fname
);
2993 xfree( outctrl
.pub
.fname
);
2994 xfree( outctrl
.pub
.newfname
);
2995 xfree( outctrl
.sec
.fname
);
2996 xfree( outctrl
.sec
.newfname
);
2999 release_parameter_list( para
);
3001 release_armor_context (outctrl
.pub
.afx
);
3002 release_armor_context (outctrl
.sec
.afx
);
3007 * Generate a keypair (fname is only used in batch mode) If
3008 * CARD_SERIALNO is not NULL the function will create the keys on an
3009 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
3010 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
3011 * generate in software, imported to the card and a backup file
3012 * written to directory given by this argument .
3015 generate_keypair (const char *fname
, const char *card_serialno
,
3016 const char *backup_encryption_dir
)
3026 struct para_data_s
*para
= NULL
;
3027 struct para_data_s
*r
;
3028 struct output_control_s outctrl
;
3031 memset( &outctrl
, 0, sizeof( outctrl
) );
3033 if (opt
.batch
&& card_serialno
)
3035 /* We don't yet support unattended key generation. */
3036 log_error (_("can't do this in batch mode\n"));
3042 read_parameter_file( fname
);
3048 #ifdef ENABLE_CARD_SUPPORT
3049 r
= xcalloc (1, sizeof *r
+ strlen (card_serialno
) );
3051 strcpy( r
->u
.value
, card_serialno
);
3055 algo
= PUBKEY_ALGO_RSA
;
3057 r
= xcalloc (1, sizeof *r
+ 20 );
3059 sprintf( r
->u
.value
, "%d", algo
);
3062 r
= xcalloc (1, sizeof *r
+ 20 );
3064 strcpy (r
->u
.value
, "sign");
3068 r
= xcalloc (1, sizeof *r
+ 20 );
3069 r
->key
= pSUBKEYTYPE
;
3070 sprintf( r
->u
.value
, "%d", algo
);
3073 r
= xcalloc (1, sizeof *r
+ 20 );
3074 r
->key
= pSUBKEYUSAGE
;
3075 strcpy (r
->u
.value
, "encrypt");
3079 r
= xcalloc (1, sizeof *r
+ 20 );
3080 r
->key
= pAUTHKEYTYPE
;
3081 sprintf( r
->u
.value
, "%d", algo
);
3085 if (backup_encryption_dir
)
3087 r
= xcalloc (1, sizeof *r
+ strlen (backup_encryption_dir
) );
3088 r
->key
= pBACKUPENCDIR
;
3089 strcpy (r
->u
.value
, backup_encryption_dir
);
3093 #endif /*ENABLE_CARD_SUPPORT*/
3099 algo
= ask_algo (0, &subkey_algo
, &use
);
3102 /* Create primary and subkey at once. */
3104 r
= xmalloc_clear( sizeof *r
+ 20 );
3106 sprintf( r
->u
.value
, "%d", algo
);
3109 nbits
= ask_keysize (algo
, 0);
3110 r
= xmalloc_clear( sizeof *r
+ 20 );
3111 r
->key
= pKEYLENGTH
;
3112 sprintf( r
->u
.value
, "%u", nbits
);
3115 r
= xmalloc_clear( sizeof *r
+ 20 );
3117 strcpy( r
->u
.value
, "sign" );
3121 r
= xmalloc_clear( sizeof *r
+ 20 );
3122 r
->key
= pSUBKEYTYPE
;
3123 sprintf( r
->u
.value
, "%d", subkey_algo
);
3126 r
= xmalloc_clear( sizeof *r
+ 20 );
3127 r
->key
= pSUBKEYUSAGE
;
3128 strcpy( r
->u
.value
, "encrypt" );
3134 r
= xmalloc_clear( sizeof *r
+ 20 );
3136 sprintf( r
->u
.value
, "%d", algo
);
3142 r
= xmalloc_clear( sizeof *r
+ 25 );
3144 sprintf( r
->u
.value
, "%s%s%s",
3145 (use
& PUBKEY_USAGE_SIG
)? "sign ":"",
3146 (use
& PUBKEY_USAGE_ENC
)? "encrypt ":"",
3147 (use
& PUBKEY_USAGE_AUTH
)? "auth":"" );
3154 nbits
= ask_keysize (both
? subkey_algo
: algo
, nbits
);
3155 r
= xmalloc_clear( sizeof *r
+ 20 );
3156 r
->key
= both
? pSUBKEYLENGTH
: pKEYLENGTH
;
3157 sprintf( r
->u
.value
, "%u", nbits
);
3162 expire
= ask_expire_interval(0,NULL
);
3163 r
= xmalloc_clear( sizeof *r
+ 20 );
3164 r
->key
= pKEYEXPIRE
;
3165 r
->u
.expire
= expire
;
3168 r
= xmalloc_clear( sizeof *r
+ 20 );
3169 r
->key
= pSUBKEYEXPIRE
;
3170 r
->u
.expire
= expire
;
3174 uid
= ask_user_id (0, NULL
);
3177 log_error(_("Key generation canceled.\n"));
3178 release_parameter_list( para
);
3181 r
= xmalloc_clear( sizeof *r
+ strlen(uid
) );
3183 strcpy( r
->u
.value
, uid
);
3188 dek
= card_serialno
? NULL
: do_ask_passphrase (&s2k
, 0, &canceled
);
3191 r
= xmalloc_clear( sizeof *r
);
3192 r
->key
= pPASSPHRASE_DEK
;
3196 r
= xmalloc_clear( sizeof *r
);
3197 r
->key
= pPASSPHRASE_S2K
;
3204 log_error (_("Key generation canceled.\n"));
3206 proc_parameter_file( para
, "[internal]", &outctrl
, !!card_serialno
);
3207 release_parameter_list( para
);
3211 #ifdef ENABLE_CARD_SUPPORT
3212 /* Generate a raw key and return it as a secret key packet. The
3213 function will ask for the passphrase and return a protected as well
3214 as an unprotected copy of a new secret key packet. 0 is returned
3215 on success and the caller must then free the returned values. */
3217 generate_raw_key (int algo
, unsigned int nbits
, u32 created_at
,
3218 PKT_secret_key
**r_sk_unprotected
,
3219 PKT_secret_key
**r_sk_protected
)
3223 STRING2KEY
*s2k
= NULL
;
3224 PKT_secret_key
*sk
= NULL
;
3226 size_t nskey
, npkey
;
3227 gcry_sexp_t s_parms
, s_key
;
3230 npkey
= pubkey_get_npkey (algo
);
3231 nskey
= pubkey_get_nskey (algo
);
3232 assert (nskey
<= PUBKEY_MAX_NSKEY
&& npkey
< nskey
);
3237 log_info (_("keysize invalid; using %u bits\n"), nbits
);
3242 nbits
= ((nbits
+ 31) / 32) * 32;
3243 log_info(_("keysize rounded up to %u bits\n"), nbits
);
3246 dek
= do_ask_passphrase (&s2k
, 1, &canceled
);
3249 rc
= gpg_error (GPG_ERR_CANCELED
);
3253 sk
= xmalloc_clear (sizeof *sk
);
3254 sk
->timestamp
= created_at
;
3256 sk
->pubkey_algo
= algo
;
3258 if ( !is_RSA (algo
) )
3260 log_error ("only RSA is supported for offline generated keys\n");
3261 rc
= gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
3264 rc
= gcry_sexp_build (&s_parms
, NULL
,
3265 "(genkey(rsa(nbits %d)))",
3268 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc
));
3269 rc
= gcry_pk_genkey (&s_key
, s_parms
);
3270 gcry_sexp_release (s_parms
);
3273 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc
) );
3276 rc
= key_from_sexp (sk
->skey
, s_key
, "private-key", "nedpqu");
3277 gcry_sexp_release (s_key
);
3280 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc
) );
3284 for (i
=npkey
; i
< nskey
; i
++)
3285 sk
->csum
+= checksum_mpi (sk
->skey
[i
]);
3287 if (r_sk_unprotected
)
3288 *r_sk_unprotected
= copy_secret_key (NULL
, sk
);
3290 rc
= genhelp_protect (dek
, s2k
, sk
);
3296 *r_sk_protected
= sk
;
3302 free_secret_key (sk
);
3307 #endif /* ENABLE_CARD_SUPPORT */
3309 /* Create and delete a dummy packet to start off a list of kbnodes. */
3311 start_tree(KBNODE
*tree
)
3315 pkt
=xmalloc_clear(sizeof(*pkt
));
3316 pkt
->pkttype
=PKT_NONE
;
3317 *tree
=new_kbnode(pkt
);
3318 delete_kbnode(*tree
);
3323 do_generate_keypair (struct para_data_s
*para
,
3324 struct output_control_s
*outctrl
, int card
)
3326 KBNODE pub_root
= NULL
;
3327 KBNODE sec_root
= NULL
;
3328 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3330 struct revocation_key
*revkey
;
3335 if( outctrl
->dryrun
)
3337 log_info("dry-run mode - key generation skipped\n");
3341 if ( outctrl
->use_files
)
3343 if ( outctrl
->pub
.newfname
)
3345 iobuf_close(outctrl
->pub
.stream
);
3346 outctrl
->pub
.stream
= NULL
;
3347 if (outctrl
->pub
.fname
)
3348 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->pub
.fname
);
3349 xfree( outctrl
->pub
.fname
);
3350 outctrl
->pub
.fname
= outctrl
->pub
.newfname
;
3351 outctrl
->pub
.newfname
= NULL
;
3353 if (is_secured_filename (outctrl
->pub
.fname
) )
3355 outctrl
->pub
.stream
= NULL
;
3359 outctrl
->pub
.stream
= iobuf_create( outctrl
->pub
.fname
);
3360 if (!outctrl
->pub
.stream
)
3362 log_error(_("can't create `%s': %s\n"), outctrl
->pub
.newfname
,
3368 outctrl
->pub
.afx
->what
= 1;
3369 push_armor_filter (outctrl
->pub
.afx
, outctrl
->pub
.stream
);
3372 if (outctrl
->sec
.newfname
)
3376 iobuf_close(outctrl
->sec
.stream
);
3377 outctrl
->sec
.stream
= NULL
;
3378 if (outctrl
->sec
.fname
)
3379 iobuf_ioctl (NULL
, 2, 0, (char*)outctrl
->sec
.fname
);
3380 xfree( outctrl
->sec
.fname
);
3381 outctrl
->sec
.fname
= outctrl
->sec
.newfname
;
3382 outctrl
->sec
.newfname
= NULL
;
3384 oldmask
= umask (077);
3385 if (is_secured_filename (outctrl
->sec
.fname
) )
3387 outctrl
->sec
.stream
= NULL
;
3391 outctrl
->sec
.stream
= iobuf_create( outctrl
->sec
.fname
);
3393 if (!outctrl
->sec
.stream
)
3395 log_error(_("can't create `%s': %s\n"), outctrl
->sec
.newfname
,
3401 outctrl
->sec
.afx
->what
= 5;
3402 push_armor_filter (outctrl
->sec
.afx
, outctrl
->sec
.stream
);
3405 assert( outctrl
->pub
.stream
);
3406 assert( outctrl
->sec
.stream
);
3409 log_info (_("writing public key to `%s'\n"), outctrl
->pub
.fname
);
3411 log_info (_("writing secret key stub to `%s'\n"),
3412 outctrl
->sec
.fname
);
3414 log_info(_("writing secret key to `%s'\n"), outctrl
->sec
.fname
);
3419 /* We create the packets as a tree of kbnodes. Because the
3420 structure we create is known in advance we simply generate a
3421 linked list. The first packet is a dummy packet which we flag as
3422 deleted. The very first packet must always be a KEY packet. */
3424 start_tree (&pub_root
);
3425 start_tree (&sec_root
);
3427 timestamp
= get_parameter_u32 (para
, pKEYCREATIONDATE
);
3429 timestamp
= make_timestamp ();
3431 /* Note that, depending on the backend (i.e. the used scdaemon
3432 version), the card key generation may update TIMESTAMP for each
3433 key. Thus we need to pass TIMESTAMP to all signing function to
3434 make sure that the binding signature is done using the timestamp
3435 of the corresponding (sub)key and not that of the primary key.
3436 An alternative implementation could tell the signing function the
3437 node of the subkey but that is more work than just to pass the
3438 current timestamp. */
3442 rc
= do_create (get_parameter_algo( para
, pKEYTYPE
),
3443 get_parameter_uint( para
, pKEYLENGTH
),
3445 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3446 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3449 get_parameter_u32( para
, pKEYEXPIRE
), 0 );
3453 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 1, 1, pub_root
, sec_root
, NULL
,
3455 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3458 pri_sk
= sec_root
->next
->pkt
->pkt
.secret_key
;
3463 if(!rc
&& (revkey
=get_parameter_revkey(para
,pREVOKER
)))
3465 rc
= write_direct_sig (pub_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3467 rc
= write_direct_sig (sec_root
, pub_root
, pri_sk
, revkey
, timestamp
);
3470 if( !rc
&& (s
=get_parameter_value(para
, pUSERID
)) )
3472 write_uid (pub_root
, s
);
3473 write_uid (sec_root
, s
);
3475 rc
= write_selfsigs (sec_root
, pub_root
, pri_sk
,
3476 get_parameter_uint (para
, pKEYUSAGE
), timestamp
);
3479 /* Write the auth key to the card before the encryption key. This
3480 is a partial workaround for a PGP bug (as of this writing, all
3481 versions including 8.1), that causes it to try and encrypt to
3482 the most recent subkey regardless of whether that subkey is
3483 actually an encryption type. In this case, the auth key is an
3484 RSA key so it succeeds. */
3486 if (!rc
&& card
&& get_parameter (para
, pAUTHKEYTYPE
))
3488 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 3, 0, pub_root
, sec_root
, NULL
,
3490 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3493 rc
= write_keybinding (pub_root
, pub_root
, pri_sk
, sub_sk
,
3494 PUBKEY_USAGE_AUTH
, timestamp
);
3496 rc
= write_keybinding (sec_root
, pub_root
, pri_sk
, sub_sk
,
3497 PUBKEY_USAGE_AUTH
, timestamp
);
3500 if( !rc
&& get_parameter( para
, pSUBKEYTYPE
) )
3504 rc
= do_create( get_parameter_algo( para
, pSUBKEYTYPE
),
3505 get_parameter_uint( para
, pSUBKEYLENGTH
),
3507 get_parameter_dek( para
, pPASSPHRASE_DEK
),
3508 get_parameter_s2k( para
, pPASSPHRASE_S2K
),
3511 get_parameter_u32( para
, pSUBKEYEXPIRE
), 1 );
3515 if ((s
= get_parameter_value (para
, pBACKUPENCDIR
)))
3517 /* A backup of the encryption key has been requested.
3518 Generate the key in software and import it then to
3519 the card. Write a backup file. */
3520 rc
= gen_card_key_with_backup (PUBKEY_ALGO_RSA
, 2, 0,
3523 get_parameter_u32 (para
,
3529 rc
= gen_card_key (PUBKEY_ALGO_RSA
, 2, 0, pub_root
, sec_root
,
3532 get_parameter_u32 (para
, pKEYEXPIRE
), para
);
3537 rc
= write_keybinding(pub_root
, pub_root
, pri_sk
, sub_sk
,
3538 get_parameter_uint (para
, pSUBKEYUSAGE
),
3541 rc
= write_keybinding(sec_root
, pub_root
, pri_sk
, sub_sk
,
3542 get_parameter_uint (para
, pSUBKEYUSAGE
),
3547 if (!rc
&& outctrl
->use_files
) /* Direct write to specified files. */
3549 rc
= write_keyblock( outctrl
->pub
.stream
, pub_root
);
3551 log_error ("can't write public key: %s\n", g10_errstr(rc
) );
3554 rc
= write_keyblock( outctrl
->sec
.stream
, sec_root
);
3556 log_error ("can't write secret key: %s\n", g10_errstr(rc
) );
3559 else if (!rc
) /* Write to the standard keyrings. */
3561 KEYDB_HANDLE pub_hd
= keydb_new (0);
3562 KEYDB_HANDLE sec_hd
= keydb_new (1);
3564 rc
= keydb_locate_writable (pub_hd
, NULL
);
3566 log_error (_("no writable public keyring found: %s\n"),
3571 rc
= keydb_locate_writable (sec_hd
, NULL
);
3573 log_error (_("no writable secret keyring found: %s\n"),
3577 if (!rc
&& opt
.verbose
)
3579 log_info (_("writing public key to `%s'\n"),
3580 keydb_get_resource_name (pub_hd
));
3582 log_info (_("writing secret key stub to `%s'\n"),
3583 keydb_get_resource_name (sec_hd
));
3585 log_info (_("writing secret key to `%s'\n"),
3586 keydb_get_resource_name (sec_hd
));
3591 rc
= keydb_insert_keyblock (pub_hd
, pub_root
);
3593 log_error (_("error writing public keyring `%s': %s\n"),
3594 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3599 rc
= keydb_insert_keyblock (sec_hd
, sec_root
);
3601 log_error (_("error writing secret keyring `%s': %s\n"),
3602 keydb_get_resource_name (pub_hd
), g10_errstr(rc
));
3605 keydb_release (pub_hd
);
3606 keydb_release (sec_hd
);
3613 no_enc_rsa
= (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_RSA
3614 && get_parameter_uint (para
, pKEYUSAGE
)
3615 && !((get_parameter_uint (para
, pKEYUSAGE
)
3616 & PUBKEY_USAGE_ENC
)) );
3618 pk
= find_kbnode (pub_root
, PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3620 keyid_from_pk(pk
,pk
->main_keyid
);
3621 register_trusted_keyid(pk
->main_keyid
);
3623 update_ownertrust (pk
, ((get_ownertrust (pk
) & ~TRUST_MASK
)
3624 | TRUST_ULTIMATE
));
3628 tty_printf (_("public and secret key created and signed.\n") );
3630 list_keyblock(pub_root
,0,1,NULL
);
3635 && (get_parameter_algo (para
, pKEYTYPE
) == PUBKEY_ALGO_DSA
3637 && !get_parameter (para
, pSUBKEYTYPE
) )
3639 tty_printf(_("Note that this key cannot be used for "
3640 "encryption. You may want to use\n"
3641 "the command \"--edit-key\" to generate a "
3642 "subkey for this purpose.\n") );
3650 log_error ("key generation failed: %s\n", g10_errstr(rc
) );
3652 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3653 write_status_error (card
? "card_key_generate":"key_generate", rc
);
3654 print_status_key_not_created ( get_parameter_value (para
, pHANDLE
) );
3658 PKT_public_key
*pk
= find_kbnode (pub_root
,
3659 PKT_PUBLIC_KEY
)->pkt
->pkt
.public_key
;
3660 print_status_key_created (did_sub
? 'B':'P', pk
,
3661 get_parameter_value (para
, pHANDLE
));
3663 release_kbnode( pub_root
);
3664 release_kbnode( sec_root
);
3666 if (pri_sk
&& !card
) /* The unprotected secret key unless we */
3667 free_secret_key (pri_sk
); /* have a shallow copy in card mode. */
3669 free_secret_key(sub_sk
);
3673 /* Add a new subkey to an existing key. Returns true if a new key has
3674 been generated and put into the keyblocks. */
3676 generate_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
)
3680 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
= NULL
;
3685 char *passphrase
= NULL
;
3687 STRING2KEY
*s2k
= NULL
;
3692 /* Break out the primary secret key. */
3693 node
= find_kbnode( sec_keyblock
, PKT_SECRET_KEY
);
3696 log_error ("Oops; secret key not found anymore!\n");
3700 /* Make a copy of the sk to keep the protected one in the keyblock. */
3701 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3703 cur_time
= make_timestamp();
3705 if (pri_sk
->timestamp
> cur_time
)
3707 ulong d
= pri_sk
->timestamp
- cur_time
;
3708 log_info ( d
==1 ? _("key has been created %lu second "
3709 "in future (time warp or clock problem)\n")
3710 : _("key has been created %lu seconds "
3711 "in future (time warp or clock problem)\n"), d
);
3712 if (!opt
.ignore_time_conflict
)
3714 rc
= G10ERR_TIME_CONFLICT
;
3719 if (pri_sk
->version
< 4)
3721 log_info (_("NOTE: creating subkeys for v3 keys "
3722 "is not OpenPGP compliant\n"));
3726 if (pri_sk
->is_protected
&& pri_sk
->protect
.s2k
.mode
== 1001)
3728 tty_printf (_("Secret parts of primary key are not available.\n"));
3729 rc
= G10ERR_NO_SECKEY
;
3734 /* Unprotect to get the passphrase. */
3735 switch (is_secret_key_protected (pri_sk
) )
3738 rc
= G10ERR_PUBKEY_ALGO
;
3741 tty_printf (_("This key is not protected.\n"));
3744 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3748 tty_printf (_("Key is protected.\n"));
3749 rc
= check_secret_key ( pri_sk
, 0 );
3751 passphrase
= get_last_passphrase();
3757 algo
= ask_algo (1, NULL
, &use
);
3759 nbits
= ask_keysize (algo
, 0);
3760 expire
= ask_expire_interval (0, NULL
);
3761 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3762 _("Really create? (y/N) ")))
3767 dek
= do_ask_passphrase (&s2k
, 0, &canceled
);
3768 else if (passphrase
)
3770 s2k
= xmalloc_secure ( sizeof *s2k
);
3771 s2k
->mode
= opt
.s2k_mode
;
3772 s2k
->hash_algo
= S2K_DIGEST_ALGO
;
3773 set_next_passphrase ( passphrase
);
3774 dek
= passphrase_to_dek (NULL
, 0, opt
.s2k_cipher_algo
, s2k
, 2,
3779 rc
= GPG_ERR_CANCELED
;
3782 rc
= do_create (algo
, nbits
, pub_keyblock
, sec_keyblock
,
3783 dek
, s2k
, &sub_sk
, cur_time
, expire
, 1 );
3785 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3788 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3793 write_status_text (STATUS_KEY_CREATED
, "S");
3798 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3802 /* Release the copy of the (now unprotected) secret keys. */
3804 free_secret_key (pri_sk
);
3806 free_secret_key (sub_sk
);
3807 set_next_passphrase (NULL
);
3812 #ifdef ENABLE_CARD_SUPPORT
3813 /* Generate a subkey on a card. */
3815 generate_card_subkeypair (KBNODE pub_keyblock
, KBNODE sec_keyblock
,
3816 int keyno
, const char *serialno
)
3820 PKT_secret_key
*pri_sk
= NULL
, *sub_sk
;
3824 char *passphrase
= NULL
;
3826 struct para_data_s
*para
= NULL
;
3828 assert (keyno
>= 1 && keyno
<= 3);
3830 para
= xcalloc (1, sizeof *para
+ strlen (serialno
) );
3831 para
->key
= pSERIALNO
;
3832 strcpy (para
->u
.value
, serialno
);
3834 /* Break out the primary secret key */
3835 node
= find_kbnode (sec_keyblock
, PKT_SECRET_KEY
);
3838 log_error("Oops; secret key not found anymore!\n");
3842 /* Make a copy of the sk to keep the protected one in the keyblock */
3843 pri_sk
= copy_secret_key (NULL
, node
->pkt
->pkt
.secret_key
);
3845 cur_time
= make_timestamp();
3846 if (pri_sk
->timestamp
> cur_time
)
3848 ulong d
= pri_sk
->timestamp
- cur_time
;
3849 log_info (d
==1 ? _("key has been created %lu second "
3850 "in future (time warp or clock problem)\n")
3851 : _("key has been created %lu seconds "
3852 "in future (time warp or clock problem)\n"), d
);
3853 if (!opt
.ignore_time_conflict
)
3855 rc
= G10ERR_TIME_CONFLICT
;
3860 if (pri_sk
->version
< 4)
3862 log_info (_("NOTE: creating subkeys for v3 keys "
3863 "is not OpenPGP compliant\n"));
3867 /* Unprotect to get the passphrase. */
3868 switch( is_secret_key_protected (pri_sk
) )
3871 rc
= G10ERR_PUBKEY_ALGO
;
3874 tty_printf("This key is not protected.\n");
3877 tty_printf("Key is protected.\n");
3878 rc
= check_secret_key( pri_sk
, 0 );
3880 passphrase
= get_last_passphrase();
3886 algo
= PUBKEY_ALGO_RSA
;
3887 expire
= ask_expire_interval (0,NULL
);
3889 use
= PUBKEY_USAGE_SIG
;
3890 else if (keyno
== 2)
3891 use
= PUBKEY_USAGE_ENC
;
3893 use
= PUBKEY_USAGE_AUTH
;
3894 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3895 _("Really create? (y/N) ")))
3899 set_next_passphrase (passphrase
);
3901 /* Note, that depending on the backend, the card key generation may
3903 rc
= gen_card_key (algo
, keyno
, 0, pub_keyblock
, sec_keyblock
,
3904 &sub_sk
, &cur_time
, expire
, para
);
3906 rc
= write_keybinding (pub_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3909 rc
= write_keybinding (sec_keyblock
, pub_keyblock
, pri_sk
, sub_sk
,
3914 write_status_text (STATUS_KEY_CREATED
, "S");
3919 log_error (_("Key generation failed: %s\n"), g10_errstr(rc
) );
3921 /* Release the copy of the (now unprotected) secret keys. */
3923 free_secret_key (pri_sk
);
3924 set_next_passphrase( NULL
);
3925 release_parameter_list (para
);
3928 #endif /* !ENABLE_CARD_SUPPORT */
3932 * Write a keyblock to an output stream
3935 write_keyblock( IOBUF out
, KBNODE node
)
3937 for( ; node
; node
= node
->next
)
3939 if(!is_deleted_kbnode(node
))
3941 int rc
= build_packet( out
, node
->pkt
);
3944 log_error("build_packet(%d) failed: %s\n",
3945 node
->pkt
->pkttype
, g10_errstr(rc
) );
3955 /* Note that timestamp is an in/out arg. */
3957 gen_card_key (int algo
, int keyno
, int is_primary
,
3958 KBNODE pub_root
, KBNODE sec_root
, PKT_secret_key
**ret_sk
,
3959 u32
*timestamp
, u32 expireval
, struct para_data_s
*para
)
3961 #ifdef ENABLE_CARD_SUPPORT
3964 struct agent_card_genkey_s info
;
3969 assert (algo
== PUBKEY_ALGO_RSA
);
3971 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
3972 rc
= agent_scd_genkey (&info
, keyno
, 1, NULL
, *timestamp
);
3973 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
3975 /* tty_printf ("\n"); */
3976 /* log_error ("WARNING: key does already exists!\n"); */
3977 /* tty_printf ("\n"); */
3978 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
3979 /* _("Replace existing key? "))) */
3980 /* rc = agent_scd_genkey (&info, keyno, 1); */
3985 log_error ("key generation failed: %s\n", gpg_strerror (rc
));
3988 if ( !info
.n
|| !info
.e
)
3990 log_error ("communication error with SCD\n");
3991 gcry_mpi_release (info
.n
);
3992 gcry_mpi_release (info
.e
);
3993 return gpg_error (GPG_ERR_GENERAL
);
3996 if (*timestamp
!= info
.created_at
)
3997 log_info ("Note that the key does not use the suggested creation date\n");
3998 *timestamp
= info
.created_at
;
4000 pk
= xcalloc (1, sizeof *pk
);
4001 sk
= xcalloc (1, sizeof *sk
);
4002 sk
->timestamp
= pk
->timestamp
= info
.created_at
;
4003 sk
->version
= pk
->version
= 4;
4005 sk
->expiredate
= pk
->expiredate
= pk
->timestamp
+ expireval
;
4006 sk
->pubkey_algo
= pk
->pubkey_algo
= algo
;
4007 pk
->pkey
[0] = info
.n
;
4008 pk
->pkey
[1] = info
.e
;
4009 sk
->skey
[0] = gcry_mpi_copy (pk
->pkey
[0]);
4010 sk
->skey
[1] = gcry_mpi_copy (pk
->pkey
[1]);
4011 sk
->skey
[2] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
4012 sk
->is_protected
= 1;
4013 sk
->protect
.s2k
.mode
= 1002;
4014 s
= get_parameter_value (para
, pSERIALNO
);
4017 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
4018 sk
->protect
.ivlen
++, s
+= 2)
4019 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
4025 pkt
= xcalloc (1,sizeof *pkt
);
4026 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
4027 pkt
->pkt
.public_key
= pk
;
4028 add_kbnode(pub_root
, new_kbnode( pkt
));
4030 pkt
= xcalloc (1,sizeof *pkt
);
4031 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
4032 pkt
->pkt
.secret_key
= sk
;
4033 add_kbnode(sec_root
, new_kbnode( pkt
));
4038 #endif /*!ENABLE_CARD_SUPPORT*/
4044 gen_card_key_with_backup (int algo
, int keyno
, int is_primary
,
4045 KBNODE pub_root
, KBNODE sec_root
,
4047 u32 expireval
, struct para_data_s
*para
,
4048 const char *backup_dir
)
4050 #ifdef ENABLE_CARD_SUPPORT
4054 PKT_secret_key
*sk
, *sk_unprotected
= NULL
, *sk_protected
= NULL
;
4060 /* Get the size of the key directly from the card. */
4062 struct agent_card_info_s info
;
4064 memset (&info
, 0, sizeof info
);
4065 if (!agent_scd_getattr ("KEY-ATTR", &info
)
4066 && info
.key_attr
[1].algo
)
4067 nbits
= info
.key_attr
[1].nbits
;
4069 nbits
= 1024; /* All pre-v2.0 cards. */
4070 agent_release_card_info (&info
);
4073 /* Create a key of this size in memory. */
4074 rc
= generate_raw_key (algo
, nbits
, timestamp
,
4075 &sk_unprotected
, &sk_protected
);
4079 /* Store the key to the card. */
4080 rc
= save_unprotected_key_to_card (sk_unprotected
, keyno
);
4083 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc
));
4084 free_secret_key (sk_unprotected
);
4085 free_secret_key (sk_protected
);
4086 write_status_error ("save_key_to_card", rc
);
4090 /* Get rid of the secret key parameters and store the serial numer. */
4091 sk
= sk_unprotected
;
4092 n
= pubkey_get_nskey (sk
->pubkey_algo
);
4093 for (i
=pubkey_get_npkey (sk
->pubkey_algo
); i
< n
; i
++)
4095 gcry_mpi_release (sk
->skey
[i
]);
4098 i
= pubkey_get_npkey (sk
->pubkey_algo
);
4099 sk
->skey
[i
] = gcry_mpi_set_opaque (NULL
, xstrdup ("dummydata"), 10*8);
4100 sk
->is_protected
= 1;
4101 sk
->protect
.s2k
.mode
= 1002;
4102 s
= get_parameter_value (para
, pSERIALNO
);
4104 for (sk
->protect
.ivlen
=0; sk
->protect
.ivlen
< 16 && *s
&& s
[1];
4105 sk
->protect
.ivlen
++, s
+= 2)
4106 sk
->protect
.iv
[sk
->protect
.ivlen
] = xtoi_2 (s
);
4108 /* Now write the *protected* secret key to the file. */
4110 char name_buffer
[50];
4115 keyid_from_sk (sk
, NULL
);
4116 snprintf (name_buffer
, sizeof name_buffer
, "sk_%08lX%08lX.gpg",
4117 (ulong
)sk
->keyid
[0], (ulong
)sk
->keyid
[1]);
4119 fname
= make_filename (backup_dir
, name_buffer
, NULL
);
4120 oldmask
= umask (077);
4121 if (is_secured_filename (fname
))
4127 fp
= iobuf_create (fname
);
4131 rc
= gpg_error_from_syserror ();
4132 log_error (_("can't create backup file `%s': %s\n"),
4133 fname
, strerror(errno
) );
4135 free_secret_key (sk_unprotected
);
4136 free_secret_key (sk_protected
);
4140 pkt
= xcalloc (1, sizeof *pkt
);
4141 pkt
->pkttype
= PKT_SECRET_KEY
;
4142 pkt
->pkt
.secret_key
= sk_protected
;
4143 sk_protected
= NULL
;
4145 rc
= build_packet (fp
, pkt
);
4148 log_error("build packet failed: %s\n", g10_errstr(rc
) );
4153 unsigned char array
[MAX_FINGERPRINT_LEN
];
4157 iobuf_ioctl (NULL
, 2, 0, (char*)fname
);
4158 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname
);
4160 fingerprint_from_sk (sk
, array
, &n
);
4161 p
= fprbuf
= xmalloc (MAX_FINGERPRINT_LEN
*2 + 1 + 1);
4162 for (i
=0; i
< n
; i
++, p
+= 2)
4163 sprintf (p
, "%02X", array
[i
]);
4167 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED
,
4169 fname
, strlen (fname
),
4178 free_secret_key (sk_unprotected
);
4183 /* Create the public key from the secret key. */
4184 pk
= xcalloc (1, sizeof *pk
);
4185 pk
->timestamp
= sk
->timestamp
;
4186 pk
->version
= sk
->version
;
4188 pk
->expiredate
= sk
->expiredate
= sk
->timestamp
+ expireval
;
4189 pk
->pubkey_algo
= sk
->pubkey_algo
;
4190 n
= pubkey_get_npkey (sk
->pubkey_algo
);
4191 for (i
=0; i
< n
; i
++)
4192 pk
->pkey
[i
] = mpi_copy (sk
->skey
[i
]);
4194 /* Build packets and add them to the node lists. */
4195 pkt
= xcalloc (1,sizeof *pkt
);
4196 pkt
->pkttype
= is_primary
? PKT_PUBLIC_KEY
: PKT_PUBLIC_SUBKEY
;
4197 pkt
->pkt
.public_key
= pk
;
4198 add_kbnode(pub_root
, new_kbnode( pkt
));
4200 pkt
= xcalloc (1,sizeof *pkt
);
4201 pkt
->pkttype
= is_primary
? PKT_SECRET_KEY
: PKT_SECRET_SUBKEY
;
4202 pkt
->pkt
.secret_key
= sk
;
4203 add_kbnode(sec_root
, new_kbnode( pkt
));
4208 #endif /*!ENABLE_CARD_SUPPORT*/
4212 #ifdef ENABLE_CARD_SUPPORT
4214 save_unprotected_key_to_card (PKT_secret_key
*sk
, int keyno
)
4217 unsigned char *rsa_n
= NULL
;
4218 unsigned char *rsa_e
= NULL
;
4219 unsigned char *rsa_p
= NULL
;
4220 unsigned char *rsa_q
= NULL
;
4221 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
4222 unsigned char *sexp
= NULL
;
4224 char numbuf
[55], numbuf2
[50];
4226 assert (is_RSA (sk
->pubkey_algo
));
4227 assert (!sk
->is_protected
);
4229 /* Copy the parameters into straight buffers. */
4230 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_n
, &rsa_n_len
, sk
->skey
[0]);
4231 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_e
, &rsa_e_len
, sk
->skey
[1]);
4232 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_p
, &rsa_p_len
, sk
->skey
[3]);
4233 gcry_mpi_aprint (GCRYMPI_FMT_USG
, &rsa_q
, &rsa_q_len
, sk
->skey
[4]);
4234 if (!rsa_n
|| !rsa_e
|| !rsa_p
|| !rsa_q
)
4236 rc
= G10ERR_INV_ARG
;
4240 /* Put the key into an S-expression. */
4241 sexp
= p
= xmalloc_secure (30
4242 + rsa_n_len
+ rsa_e_len
+ rsa_p_len
+ rsa_q_len
4243 + 4*sizeof (numbuf
) + 25 + sizeof(numbuf
) + 20);
4245 p
= stpcpy (p
,"(11:private-key(3:rsa(1:n");
4246 sprintf (numbuf
, "%u:", (unsigned int)rsa_n_len
);
4247 p
= stpcpy (p
, numbuf
);
4248 memcpy (p
, rsa_n
, rsa_n_len
);
4251 sprintf (numbuf
, ")(1:e%u:", (unsigned int)rsa_e_len
);
4252 p
= stpcpy (p
, numbuf
);
4253 memcpy (p
, rsa_e
, rsa_e_len
);
4256 sprintf (numbuf
, ")(1:p%u:", (unsigned int)rsa_p_len
);
4257 p
= stpcpy (p
, numbuf
);
4258 memcpy (p
, rsa_p
, rsa_p_len
);
4261 sprintf (numbuf
, ")(1:q%u:", (unsigned int)rsa_q_len
);
4262 p
= stpcpy (p
, numbuf
);
4263 memcpy (p
, rsa_q
, rsa_q_len
);
4266 p
= stpcpy (p
,"))(10:created-at");
4267 sprintf (numbuf2
, "%lu", (unsigned long)sk
->timestamp
);
4268 sprintf (numbuf
, "%lu:", (unsigned long)strlen (numbuf2
));
4269 p
= stpcpy (stpcpy (stpcpy (p
, numbuf
), numbuf2
), "))");
4271 /* Fixme: Unfortunately we don't have the serialnumber available -
4272 thus we can't pass it down to the agent. */
4273 rc
= agent_scd_writekey (keyno
, NULL
, sexp
, p
- sexp
);
4283 #endif /*ENABLE_CARD_SUPPORT*/