chiark / gitweb /
gpg: Fix searching for mail addresses in keyrings.
[gnupg2.git] / g10 / keygen.c
1 /* keygen.c - Generate a key pair
2  * Copyright (C) 1998-2007, 2009-2011  Free Software Foundation, Inc.
3  * Copyright (C) 2014, 2015, 2016  Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
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.
11  *
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.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30
31 #include "gpg.h"
32 #include "util.h"
33 #include "main.h"
34 #include "packet.h"
35 #include "ttyio.h"
36 #include "options.h"
37 #include "keydb.h"
38 #include "trustdb.h"
39 #include "status.h"
40 #include "i18n.h"
41 #include "keyserver-internal.h"
42 #include "call-agent.h"
43 #include "pkglue.h"
44 #include "../common/shareddefs.h"
45 #include "host2net.h"
46 #include "mbox-util.h"
47
48
49 /* The default algorithms.  If you change them remember to change them
50    also in gpg.c:gpgconf_list.  You should also check that the value
51    is inside the bounds enforced by ask_keysize and gen_xxx.  See also
52    get_keysize_range which encodes the allowed ranges.  */
53 #define DEFAULT_STD_KEY_PARAM  "rsa2048/cert,sign+rsa2048/encr"
54 #define FUTURE_STD_KEY_PARAM   "ed25519/cert,sign+cv25519/encr"
55
56 /* When generating keys using the streamlined key generation dialog,
57    use this as a default expiration interval.  */
58 const char *default_expiration_interval = "2y";
59
60 /* Flag bits used during key generation.  */
61 #define KEYGEN_FLAG_NO_PROTECTION 1
62 #define KEYGEN_FLAG_TRANSIENT_KEY 2
63
64 /* Maximum number of supported algorithm preferences.  */
65 #define MAX_PREFS 30
66
67 enum para_name {
68   pKEYTYPE,
69   pKEYLENGTH,
70   pKEYCURVE,
71   pKEYUSAGE,
72   pSUBKEYTYPE,
73   pSUBKEYLENGTH,
74   pSUBKEYCURVE,
75   pSUBKEYUSAGE,
76   pAUTHKEYTYPE,
77   pNAMEREAL,
78   pNAMEEMAIL,
79   pNAMECOMMENT,
80   pPREFERENCES,
81   pREVOKER,
82   pUSERID,
83   pCREATIONDATE,
84   pKEYCREATIONDATE, /* Same in seconds since epoch.  */
85   pEXPIREDATE,
86   pKEYEXPIRE, /* in n seconds */
87   pSUBKEYEXPIRE, /* in n seconds */
88   pPASSPHRASE,
89   pSERIALNO,
90   pCARDBACKUPKEY,
91   pHANDLE,
92   pKEYSERVER
93 };
94
95 struct para_data_s {
96     struct para_data_s *next;
97     int lnr;
98     enum para_name key;
99     union {
100         u32 expire;
101         u32 creation;
102         unsigned int usage;
103         struct revocation_key revkey;
104         char value[1];
105     } u;
106 };
107
108 struct output_control_s
109 {
110   int lnr;
111   int dryrun;
112   unsigned int keygen_flags;
113   int use_files;
114   struct {
115     char  *fname;
116     char  *newfname;
117     IOBUF stream;
118     armor_filter_context_t *afx;
119   } pub;
120 };
121
122
123 struct opaque_data_usage_and_pk {
124     unsigned int usage;
125     PKT_public_key *pk;
126 };
127
128
129 static int prefs_initialized = 0;
130 static byte sym_prefs[MAX_PREFS];
131 static int nsym_prefs;
132 static byte hash_prefs[MAX_PREFS];
133 static int nhash_prefs;
134 static byte zip_prefs[MAX_PREFS];
135 static int nzip_prefs;
136 static int mdc_available,ks_modify;
137
138 static gpg_error_t parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
139                                      const char *algostr, const char *usagestr,
140                                      const char *expirestr,
141                                      int *r_algo, unsigned int *r_usage,
142                                      u32 *r_expire,
143                                      unsigned int *r_nbits, char **r_curve);
144 static void do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
145                                  struct output_control_s *outctrl, int card );
146 static int write_keyblock (iobuf_t out, kbnode_t node);
147 static gpg_error_t gen_card_key (int keyno, int algo, int is_primary,
148                                  kbnode_t pub_root, u32 *timestamp,
149                                  u32 expireval);
150 static unsigned int get_keysize_range (int algo,
151                                        unsigned int *min, unsigned int *max);
152
153
154 \f
155 /* Return the algo string for a default new key.  */
156 const char *
157 get_default_pubkey_algo (void)
158 {
159   if (opt.def_new_key_algo)
160     {
161       if (*opt.def_new_key_algo && !strchr (opt.def_new_key_algo, ':'))
162         return opt.def_new_key_algo;
163       /* To avoid checking that option every time we delay that until
164        * here.  The only thing we really need to make sure is that
165        * there is no colon in the string so that the --gpgconf-list
166        * command won't mess up its output.  */
167       log_info (_("invalid value for option '%s'\n"), "--default-new-key-algo");
168     }
169   return DEFAULT_STD_KEY_PARAM;
170 }
171
172
173 static void
174 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
175 {
176   byte array[MAX_FINGERPRINT_LEN], *s;
177   char *buf, *p;
178   size_t i, n;
179
180   if (!handle)
181     handle = "";
182
183   buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
184
185   p = buf;
186   if (letter || pk)
187     {
188       *p++ = letter;
189       if (pk)
190         {
191           *p++ = ' ';
192           fingerprint_from_pk (pk, array, &n);
193           s = array;
194           /* Fixme: Use bin2hex */
195           for (i=0; i < n ; i++, s++, p += 2)
196             snprintf (p, 3, "%02X", *s);
197         }
198     }
199   if (*handle)
200     {
201       *p++ = ' ';
202       for (i=0; handle[i] && i < 100; i++)
203         *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
204     }
205   *p = 0;
206   write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
207                      buf);
208   xfree (buf);
209 }
210
211 static void
212 print_status_key_not_created (const char *handle)
213 {
214   print_status_key_created (0, NULL, handle);
215 }
216
217
218
219 static void
220 write_uid( KBNODE root, const char *s )
221 {
222     PACKET *pkt = xmalloc_clear(sizeof *pkt );
223     size_t n = strlen(s);
224
225     pkt->pkttype = PKT_USER_ID;
226     pkt->pkt.user_id = xmalloc_clear (sizeof *pkt->pkt.user_id + n);
227     pkt->pkt.user_id->len = n;
228     pkt->pkt.user_id->ref = 1;
229     strcpy(pkt->pkt.user_id->name, s);
230     add_kbnode( root, new_kbnode( pkt ) );
231 }
232
233 static void
234 do_add_key_flags (PKT_signature *sig, unsigned int use)
235 {
236     byte buf[1];
237
238     buf[0] = 0;
239
240     /* The spec says that all primary keys MUST be able to certify. */
241     if(sig->sig_class!=0x18)
242       buf[0] |= 0x01;
243
244     if (use & PUBKEY_USAGE_SIG)
245       buf[0] |= 0x02;
246     if (use & PUBKEY_USAGE_ENC)
247         buf[0] |= 0x04 | 0x08;
248     if (use & PUBKEY_USAGE_AUTH)
249         buf[0] |= 0x20;
250
251     build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
252 }
253
254
255 int
256 keygen_add_key_expire (PKT_signature *sig, void *opaque)
257 {
258   PKT_public_key *pk = opaque;
259   byte buf[8];
260   u32  u;
261
262   if (pk->expiredate)
263     {
264       if (pk->expiredate > pk->timestamp)
265         u = pk->expiredate - pk->timestamp;
266       else
267         u = 1;
268
269       buf[0] = (u >> 24) & 0xff;
270       buf[1] = (u >> 16) & 0xff;
271       buf[2] = (u >>  8) & 0xff;
272       buf[3] = u & 0xff;
273       build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
274     }
275   else
276     {
277       /* Make sure we don't leave a key expiration subpacket lying
278          around */
279       delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
280     }
281
282   return 0;
283 }
284
285
286 /* Add the key usage (i.e. key flags) in SIG from the public keys
287  * pubkey_usage field.  OPAQUE has the public key.  */
288 int
289 keygen_add_key_flags (PKT_signature *sig, void *opaque)
290 {
291   PKT_public_key *pk = opaque;
292
293   do_add_key_flags (sig, pk->pubkey_usage);
294   return 0;
295 }
296
297
298 static int
299 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
300 {
301   struct opaque_data_usage_and_pk *oduap = opaque;
302
303   do_add_key_flags (sig, oduap->usage);
304   return keygen_add_key_expire (sig, oduap->pk);
305 }
306
307
308 static int
309 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
310 {
311     int i;
312
313     for (i=0; i < *nbuf; i++ )
314       if (buf[i] == val)
315         {
316           log_info (_("preference '%s' duplicated\n"), item);
317           return -1;
318         }
319
320     if (*nbuf >= MAX_PREFS)
321       {
322         if(type==1)
323           log_info(_("too many cipher preferences\n"));
324         else if(type==2)
325           log_info(_("too many digest preferences\n"));
326         else if(type==3)
327           log_info(_("too many compression preferences\n"));
328         else
329           BUG();
330
331         return -1;
332       }
333
334     buf[(*nbuf)++] = val;
335     return 0;
336 }
337
338 /*
339  * Parse the supplied string and use it to set the standard
340  * preferences.  The string may be in a form like the one printed by
341  * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
342  * cipher/hash/compress names.  Use NULL to set the default
343  * preferences.  Returns: 0 = okay
344  */
345 int
346 keygen_set_std_prefs (const char *string,int personal)
347 {
348     byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
349     int nsym=0, nhash=0, nzip=0, val, rc=0;
350     int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
351     char dummy_string[20*4+1]; /* Enough for 20 items. */
352
353     if (!string || !ascii_strcasecmp (string, "default"))
354       {
355         if (opt.def_preference_list)
356           string=opt.def_preference_list;
357         else
358           {
359             int any_compress = 0;
360             dummy_string[0]='\0';
361
362             /* The rationale why we use the order AES256,192,128 is
363                for compatibility reasons with PGP.  If gpg would
364                define AES128 first, we would get the somewhat
365                confusing situation:
366
367                  gpg -r pgpkey -r gpgkey  ---gives--> AES256
368                  gpg -r gpgkey -r pgpkey  ---gives--> AES
369
370                Note that by using --personal-cipher-preferences it is
371                possible to prefer AES128.
372             */
373
374             /* Make sure we do not add more than 15 items here, as we
375                could overflow the size of dummy_string.  We currently
376                have at most 12. */
377             if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
378               strcat(dummy_string,"S9 ");
379             if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
380               strcat(dummy_string,"S8 ");
381             if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
382               strcat(dummy_string,"S7 ");
383             strcat(dummy_string,"S2 "); /* 3DES */
384
385             /* The default hash algo order is:
386                  SHA-256, SHA-384, SHA-512, SHA-224, SHA-1.
387              */
388             if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
389               strcat (dummy_string, "H8 ");
390
391             if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
392               strcat (dummy_string, "H9 ");
393
394             if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
395               strcat (dummy_string, "H10 ");
396
397             if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
398               strcat (dummy_string, "H11 ");
399
400             strcat (dummy_string, "H2 "); /* SHA-1 */
401
402             if(!check_compress_algo(COMPRESS_ALGO_ZLIB))
403               {
404                 strcat(dummy_string,"Z2 ");
405                 any_compress = 1;
406               }
407
408             if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
409               {
410                 strcat(dummy_string,"Z3 ");
411                 any_compress = 1;
412               }
413
414             if(!check_compress_algo(COMPRESS_ALGO_ZIP))
415               {
416                 strcat(dummy_string,"Z1 ");
417                 any_compress = 1;
418               }
419
420             /* In case we have no compress algo at all, declare that
421                we prefer no compresssion.  */
422             if (!any_compress)
423               strcat(dummy_string,"Z0 ");
424
425             /* Remove the trailing space.  */
426             if (*dummy_string && dummy_string[strlen (dummy_string)-1] == ' ')
427               dummy_string[strlen (dummy_string)-1] = 0;
428
429             string=dummy_string;
430           }
431       }
432     else if (!ascii_strcasecmp (string, "none"))
433         string = "";
434
435     if(strlen(string))
436       {
437         char *prefstringbuf;
438         char *tok, *prefstring;
439
440         /* We need a writable string. */
441         prefstring = prefstringbuf = xstrdup (string);
442
443         while((tok=strsep(&prefstring," ,")))
444           {
445             if((val=string_to_cipher_algo (tok)))
446               {
447                 if(set_one_pref(val,1,tok,sym,&nsym))
448                   rc=-1;
449               }
450             else if((val=string_to_digest_algo (tok)))
451               {
452                 if(set_one_pref(val,2,tok,hash,&nhash))
453                   rc=-1;
454               }
455             else if((val=string_to_compress_algo(tok))>-1)
456               {
457                 if(set_one_pref(val,3,tok,zip,&nzip))
458                   rc=-1;
459               }
460             else if (ascii_strcasecmp(tok,"mdc")==0)
461               mdc=1;
462             else if (ascii_strcasecmp(tok,"no-mdc")==0)
463               mdc=0;
464             else if (ascii_strcasecmp(tok,"ks-modify")==0)
465               modify=1;
466             else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
467               modify=0;
468             else
469               {
470                 log_info (_("invalid item '%s' in preference string\n"),tok);
471                 rc=-1;
472               }
473           }
474
475         xfree (prefstringbuf);
476       }
477
478     if(!rc)
479       {
480         if(personal)
481           {
482             if(personal==PREFTYPE_SYM)
483               {
484                 xfree(opt.personal_cipher_prefs);
485
486                 if(nsym==0)
487                   opt.personal_cipher_prefs=NULL;
488                 else
489                   {
490                     int i;
491
492                     opt.personal_cipher_prefs=
493                       xmalloc(sizeof(prefitem_t *)*(nsym+1));
494
495                     for (i=0; i<nsym; i++)
496                       {
497                         opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
498                         opt.personal_cipher_prefs[i].value = sym[i];
499                       }
500
501                     opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
502                     opt.personal_cipher_prefs[i].value = 0;
503                   }
504               }
505             else if(personal==PREFTYPE_HASH)
506               {
507                 xfree(opt.personal_digest_prefs);
508
509                 if(nhash==0)
510                   opt.personal_digest_prefs=NULL;
511                 else
512                   {
513                     int i;
514
515                     opt.personal_digest_prefs=
516                       xmalloc(sizeof(prefitem_t *)*(nhash+1));
517
518                     for (i=0; i<nhash; i++)
519                       {
520                         opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
521                         opt.personal_digest_prefs[i].value = hash[i];
522                       }
523
524                     opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
525                     opt.personal_digest_prefs[i].value = 0;
526                   }
527               }
528             else if(personal==PREFTYPE_ZIP)
529               {
530                 xfree(opt.personal_compress_prefs);
531
532                 if(nzip==0)
533                   opt.personal_compress_prefs=NULL;
534                 else
535                   {
536                     int i;
537
538                     opt.personal_compress_prefs=
539                       xmalloc(sizeof(prefitem_t *)*(nzip+1));
540
541                     for (i=0; i<nzip; i++)
542                       {
543                         opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
544                         opt.personal_compress_prefs[i].value = zip[i];
545                       }
546
547                     opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
548                     opt.personal_compress_prefs[i].value = 0;
549                   }
550               }
551           }
552         else
553           {
554             memcpy (sym_prefs,  sym,  (nsym_prefs=nsym));
555             memcpy (hash_prefs, hash, (nhash_prefs=nhash));
556             memcpy (zip_prefs,  zip,  (nzip_prefs=nzip));
557             mdc_available = mdc;
558             ks_modify = modify;
559             prefs_initialized = 1;
560           }
561       }
562
563     return rc;
564 }
565
566 /* Return a fake user ID containing the preferences.  Caller must
567    free. */
568 PKT_user_id *
569 keygen_get_std_prefs(void)
570 {
571   int i,j=0;
572   PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
573
574   if(!prefs_initialized)
575     keygen_set_std_prefs(NULL,0);
576
577   uid->ref=1;
578
579   uid->prefs=xmalloc((sizeof(prefitem_t *)*
580                       (nsym_prefs+nhash_prefs+nzip_prefs+1)));
581
582   for(i=0;i<nsym_prefs;i++,j++)
583     {
584       uid->prefs[j].type=PREFTYPE_SYM;
585       uid->prefs[j].value=sym_prefs[i];
586     }
587
588   for(i=0;i<nhash_prefs;i++,j++)
589     {
590       uid->prefs[j].type=PREFTYPE_HASH;
591       uid->prefs[j].value=hash_prefs[i];
592     }
593
594   for(i=0;i<nzip_prefs;i++,j++)
595     {
596       uid->prefs[j].type=PREFTYPE_ZIP;
597       uid->prefs[j].value=zip_prefs[i];
598     }
599
600   uid->prefs[j].type=PREFTYPE_NONE;
601   uid->prefs[j].value=0;
602
603   uid->flags.mdc=mdc_available;
604   uid->flags.ks_modify=ks_modify;
605
606   return uid;
607 }
608
609 static void
610 add_feature_mdc (PKT_signature *sig,int enabled)
611 {
612     const byte *s;
613     size_t n;
614     int i;
615     char *buf;
616
617     s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
618     /* Already set or cleared */
619     if (s && n &&
620         ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
621       return;
622
623     if (!s || !n) { /* create a new one */
624         n = 1;
625         buf = xmalloc_clear (n);
626     }
627     else {
628         buf = xmalloc (n);
629         memcpy (buf, s, n);
630     }
631
632     if(enabled)
633       buf[0] |= 0x01; /* MDC feature */
634     else
635       buf[0] &= ~0x01;
636
637     /* Are there any bits set? */
638     for(i=0;i<n;i++)
639       if(buf[i]!=0)
640         break;
641
642     if(i==n)
643       delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
644     else
645       build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
646
647     xfree (buf);
648 }
649
650 static void
651 add_keyserver_modify (PKT_signature *sig,int enabled)
652 {
653   const byte *s;
654   size_t n;
655   int i;
656   char *buf;
657
658   /* The keyserver modify flag is a negative flag (i.e. no-modify) */
659   enabled=!enabled;
660
661   s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
662   /* Already set or cleared */
663   if (s && n &&
664       ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
665     return;
666
667   if (!s || !n) { /* create a new one */
668     n = 1;
669     buf = xmalloc_clear (n);
670   }
671   else {
672     buf = xmalloc (n);
673     memcpy (buf, s, n);
674   }
675
676   if(enabled)
677     buf[0] |= 0x80; /* no-modify flag */
678   else
679     buf[0] &= ~0x80;
680
681   /* Are there any bits set? */
682   for(i=0;i<n;i++)
683     if(buf[i]!=0)
684       break;
685
686   if(i==n)
687     delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
688   else
689     build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
690
691   xfree (buf);
692 }
693
694
695 int
696 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
697 {
698   (void)opaque;
699
700   if (!prefs_initialized)
701     keygen_set_std_prefs (NULL, 0);
702
703   if (nsym_prefs)
704     build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
705   else
706     {
707       delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
708       delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
709     }
710
711   if (nhash_prefs)
712     build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
713   else
714     {
715       delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
716       delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
717     }
718
719   if (nzip_prefs)
720     build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
721   else
722     {
723       delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
724       delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
725     }
726
727   /* Make sure that the MDC feature flag is set if needed.  */
728   add_feature_mdc (sig,mdc_available);
729   add_keyserver_modify (sig,ks_modify);
730   keygen_add_keyserver_url(sig,NULL);
731
732   return 0;
733 }
734
735
736 /****************
737  * Add preference to the self signature packet.
738  * This is only called for packets with version > 3.
739  */
740 int
741 keygen_add_std_prefs (PKT_signature *sig, void *opaque)
742 {
743   PKT_public_key *pk = opaque;
744
745   do_add_key_flags (sig, pk->pubkey_usage);
746   keygen_add_key_expire (sig, opaque );
747   keygen_upd_std_prefs (sig, opaque);
748   keygen_add_keyserver_url (sig,NULL);
749
750   return 0;
751 }
752
753 int
754 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
755 {
756   const char *url=opaque;
757
758   if(!url)
759     url=opt.def_keyserver_url;
760
761   if(url)
762     build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
763   else
764     delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
765
766   return 0;
767 }
768
769 int
770 keygen_add_notations(PKT_signature *sig,void *opaque)
771 {
772   struct notation *notation;
773
774   /* We always start clean */
775   delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
776   delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
777   sig->flags.notation=0;
778
779   for(notation=opaque;notation;notation=notation->next)
780     if(!notation->flags.ignore)
781       {
782         unsigned char *buf;
783         unsigned int n1,n2;
784
785         n1=strlen(notation->name);
786         if(notation->altvalue)
787           n2=strlen(notation->altvalue);
788         else if(notation->bdat)
789           n2=notation->blen;
790         else
791           n2=strlen(notation->value);
792
793         buf = xmalloc( 8 + n1 + n2 );
794
795         /* human readable or not */
796         buf[0] = notation->bdat?0:0x80;
797         buf[1] = buf[2] = buf[3] = 0;
798         buf[4] = n1 >> 8;
799         buf[5] = n1;
800         buf[6] = n2 >> 8;
801         buf[7] = n2;
802         memcpy(buf+8, notation->name, n1 );
803         if(notation->altvalue)
804           memcpy(buf+8+n1, notation->altvalue, n2 );
805         else if(notation->bdat)
806           memcpy(buf+8+n1, notation->bdat, n2 );
807         else
808           memcpy(buf+8+n1, notation->value, n2 );
809         build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
810                           (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
811                           buf, 8+n1+n2 );
812         xfree(buf);
813       }
814
815   return 0;
816 }
817
818 int
819 keygen_add_revkey (PKT_signature *sig, void *opaque)
820 {
821   struct revocation_key *revkey = opaque;
822   byte buf[2+MAX_FINGERPRINT_LEN];
823
824   buf[0] = revkey->class;
825   buf[1] = revkey->algid;
826   memcpy (&buf[2], revkey->fpr, MAX_FINGERPRINT_LEN);
827
828   build_sig_subpkt (sig, SIGSUBPKT_REV_KEY, buf, 2+MAX_FINGERPRINT_LEN);
829
830   /* All sigs with revocation keys set are nonrevocable.  */
831   sig->flags.revocable = 0;
832   buf[0] = 0;
833   build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
834
835   parse_revkeys (sig);
836
837   return 0;
838 }
839
840
841
842 /* Create a back-signature.  If TIMESTAMP is not NULL, use it for the
843    signature creation time.  */
844 gpg_error_t
845 make_backsig (PKT_signature *sig, PKT_public_key *pk,
846               PKT_public_key *sub_pk, PKT_public_key *sub_psk,
847               u32 timestamp, const char *cache_nonce)
848 {
849   gpg_error_t err;
850   PKT_signature *backsig;
851
852   cache_public_key (sub_pk);
853
854   err = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_psk, 0x19,
855                             0, timestamp, 0, NULL, NULL, cache_nonce);
856   if (err)
857     log_error ("make_keysig_packet failed for backsig: %s\n",
858                gpg_strerror (err));
859   else
860     {
861       /* Get it into a binary packed form. */
862       IOBUF backsig_out = iobuf_temp();
863       PACKET backsig_pkt;
864
865       init_packet (&backsig_pkt);
866       backsig_pkt.pkttype = PKT_SIGNATURE;
867       backsig_pkt.pkt.signature = backsig;
868       err = build_packet (backsig_out, &backsig_pkt);
869       free_packet (&backsig_pkt);
870       if (err)
871         log_error ("build_packet failed for backsig: %s\n", gpg_strerror (err));
872       else
873         {
874           size_t pktlen = 0;
875           byte *buf = iobuf_get_temp_buffer (backsig_out);
876
877           /* Remove the packet header. */
878           if(buf[0]&0x40)
879             {
880               if (buf[1] < 192)
881                 {
882                   pktlen = buf[1];
883                   buf += 2;
884                 }
885               else if(buf[1] < 224)
886                 {
887                   pktlen = (buf[1]-192)*256;
888                   pktlen += buf[2]+192;
889                   buf += 3;
890                 }
891               else if (buf[1] == 255)
892                 {
893                   pktlen = buf32_to_size_t (buf+2);
894                   buf += 6;
895                 }
896               else
897                 BUG ();
898             }
899           else
900             {
901               int mark = 1;
902
903               switch (buf[0]&3)
904                 {
905                 case 3:
906                   BUG ();
907                   break;
908
909                 case 2:
910                   pktlen  = (size_t)buf[mark++] << 24;
911                   pktlen |= buf[mark++] << 16;
912
913                 case 1:
914                   pktlen |= buf[mark++] << 8;
915
916                 case 0:
917                   pktlen |= buf[mark++];
918                 }
919
920               buf += mark;
921             }
922
923           /* Now make the binary blob into a subpacket.  */
924           build_sig_subpkt (sig, SIGSUBPKT_SIGNATURE, buf, pktlen);
925
926           iobuf_close (backsig_out);
927         }
928     }
929
930   return err;
931 }
932
933
934 /* Write a direct key signature to the first key in ROOT using the key
935    PSK.  REVKEY is describes the direct key signature and TIMESTAMP is
936    the timestamp to set on the signature.  */
937 static gpg_error_t
938 write_direct_sig (KBNODE root, PKT_public_key *psk,
939                   struct revocation_key *revkey, u32 timestamp,
940                   const char *cache_nonce)
941 {
942   gpg_error_t err;
943   PACKET *pkt;
944   PKT_signature *sig;
945   KBNODE node;
946   PKT_public_key *pk;
947
948   if (opt.verbose)
949     log_info (_("writing direct signature\n"));
950
951   /* Get the pk packet from the pub_tree. */
952   node = find_kbnode (root, PKT_PUBLIC_KEY);
953   if (!node)
954     BUG ();
955   pk = node->pkt->pkt.public_key;
956
957   /* We have to cache the key, so that the verification of the
958      signature creation is able to retrieve the public key.  */
959   cache_public_key (pk);
960
961   /* Make the signature.  */
962   err = make_keysig_packet (&sig, pk, NULL,NULL, psk, 0x1F,
963                             0, timestamp, 0,
964                             keygen_add_revkey, revkey, cache_nonce);
965   if (err)
966     {
967       log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err) );
968       return err;
969     }
970
971   pkt = xmalloc_clear (sizeof *pkt);
972   pkt->pkttype = PKT_SIGNATURE;
973   pkt->pkt.signature = sig;
974   add_kbnode (root, new_kbnode (pkt));
975   return err;
976 }
977
978
979
980 /* Write a self-signature to the first user id in ROOT using the key
981    PSK.  USE and TIMESTAMP give the extra data we need for the
982    signature.  */
983 static gpg_error_t
984 write_selfsigs (KBNODE root, PKT_public_key *psk,
985                 unsigned int use, u32 timestamp, const char *cache_nonce)
986 {
987   gpg_error_t err;
988   PACKET *pkt;
989   PKT_signature *sig;
990   PKT_user_id *uid;
991   KBNODE node;
992   PKT_public_key *pk;
993
994   if (opt.verbose)
995     log_info (_("writing self signature\n"));
996
997   /* Get the uid packet from the list. */
998   node = find_kbnode (root, PKT_USER_ID);
999   if (!node)
1000     BUG(); /* No user id packet in tree.  */
1001   uid = node->pkt->pkt.user_id;
1002
1003   /* Get the pk packet from the pub_tree. */
1004   node = find_kbnode (root, PKT_PUBLIC_KEY);
1005   if (!node)
1006     BUG();
1007   pk = node->pkt->pkt.public_key;
1008
1009   /* The usage has not yet been set - do it now. */
1010   pk->pubkey_usage = use;
1011
1012   /* We have to cache the key, so that the verification of the
1013      signature creation is able to retrieve the public key.  */
1014   cache_public_key (pk);
1015
1016   /* Make the signature.  */
1017   err = make_keysig_packet (&sig, pk, uid, NULL, psk, 0x13,
1018                             0, timestamp, 0,
1019                             keygen_add_std_prefs, pk, cache_nonce);
1020   if (err)
1021     {
1022       log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err));
1023       return err;
1024     }
1025
1026   pkt = xmalloc_clear (sizeof *pkt);
1027   pkt->pkttype = PKT_SIGNATURE;
1028   pkt->pkt.signature = sig;
1029   add_kbnode (root, new_kbnode (pkt));
1030
1031   return err;
1032 }
1033
1034
1035 /* Write the key binding signature.  If TIMESTAMP is not NULL use the
1036    signature creation time.  PRI_PSK is the key use for signing.
1037    SUB_PSK is a key used to create a back-signature; that one is only
1038    used if USE has the PUBKEY_USAGE_SIG capability.  */
1039 static int
1040 write_keybinding (KBNODE root, PKT_public_key *pri_psk, PKT_public_key *sub_psk,
1041                   unsigned int use, u32 timestamp, const char *cache_nonce)
1042 {
1043   gpg_error_t err;
1044   PACKET *pkt;
1045   PKT_signature *sig;
1046   KBNODE node;
1047   PKT_public_key *pri_pk, *sub_pk;
1048   struct opaque_data_usage_and_pk oduap;
1049
1050   if (opt.verbose)
1051     log_info(_("writing key binding signature\n"));
1052
1053   /* Get the primary pk packet from the tree.  */
1054   node = find_kbnode (root, PKT_PUBLIC_KEY);
1055   if (!node)
1056     BUG();
1057   pri_pk = node->pkt->pkt.public_key;
1058
1059   /* We have to cache the key, so that the verification of the
1060    * signature creation is able to retrieve the public key.  */
1061   cache_public_key (pri_pk);
1062
1063   /* Find the last subkey. */
1064   sub_pk = NULL;
1065   for (node = root; node; node = node->next )
1066     {
1067       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1068         sub_pk = node->pkt->pkt.public_key;
1069     }
1070   if (!sub_pk)
1071     BUG();
1072
1073   /* Make the signature.  */
1074   oduap.usage = use;
1075   oduap.pk = sub_pk;
1076   err = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_psk, 0x18,
1077                             0, timestamp, 0,
1078                             keygen_add_key_flags_and_expire, &oduap,
1079                             cache_nonce);
1080   if (err)
1081     {
1082       log_error ("make_keysig_packeto failed: %s\n", gpg_strerror (err));
1083       return err;
1084     }
1085
1086   /* Make a backsig.  */
1087   if (use & PUBKEY_USAGE_SIG)
1088     {
1089       err = make_backsig (sig, pri_pk, sub_pk, sub_psk, timestamp, cache_nonce);
1090       if (err)
1091         return err;
1092     }
1093
1094   pkt = xmalloc_clear ( sizeof *pkt );
1095   pkt->pkttype = PKT_SIGNATURE;
1096   pkt->pkt.signature = sig;
1097   add_kbnode (root, new_kbnode (pkt) );
1098   return err;
1099 }
1100
1101
1102 static gpg_error_t
1103 ecckey_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp, int algo)
1104 {
1105   gpg_error_t err;
1106   gcry_sexp_t list, l2;
1107   char *curve = NULL;
1108   int i;
1109   const char *oidstr;
1110   unsigned int nbits;
1111
1112   array[0] = NULL;
1113   array[1] = NULL;
1114   array[2] = NULL;
1115
1116   list = gcry_sexp_find_token (sexp, "public-key", 0);
1117   if (!list)
1118     return gpg_error (GPG_ERR_INV_OBJ);
1119   l2 = gcry_sexp_cadr (list);
1120   gcry_sexp_release (list);
1121   list = l2;
1122   if (!list)
1123     return gpg_error (GPG_ERR_NO_OBJ);
1124
1125   l2 = gcry_sexp_find_token (list, "curve", 0);
1126   if (!l2)
1127     {
1128       err = gpg_error (GPG_ERR_NO_OBJ);
1129       goto leave;
1130     }
1131   curve = gcry_sexp_nth_string (l2, 1);
1132   if (!curve)
1133     {
1134       err = gpg_error (GPG_ERR_NO_OBJ);
1135       goto leave;
1136     }
1137   gcry_sexp_release (l2);
1138   oidstr = openpgp_curve_to_oid (curve, &nbits);
1139   if (!oidstr)
1140     {
1141       /* That can't happen because we used one of the curves
1142          gpg_curve_to_oid knows about.  */
1143       err = gpg_error (GPG_ERR_INV_OBJ);
1144       goto leave;
1145     }
1146   err = openpgp_oid_from_str (oidstr, &array[0]);
1147   if (err)
1148     goto leave;
1149
1150   l2 = gcry_sexp_find_token (list, "q", 0);
1151   if (!l2)
1152     {
1153       err = gpg_error (GPG_ERR_NO_OBJ);
1154       goto leave;
1155     }
1156   array[1] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1157   gcry_sexp_release (l2);
1158   if (!array[1])
1159     {
1160       err = gpg_error (GPG_ERR_INV_OBJ);
1161       goto leave;
1162     }
1163   gcry_sexp_release (list);
1164
1165   if (algo == PUBKEY_ALGO_ECDH)
1166     {
1167       array[2] = pk_ecdh_default_params (nbits);
1168       if (!array[2])
1169         {
1170           err = gpg_error_from_syserror ();
1171           goto leave;
1172         }
1173     }
1174
1175  leave:
1176   xfree (curve);
1177   if (err)
1178     {
1179       for (i=0; i < 3; i++)
1180         {
1181           gcry_mpi_release (array[i]);
1182           array[i] = NULL;
1183         }
1184     }
1185   return err;
1186 }
1187
1188
1189 /* Extract key parameters from SEXP and store them in ARRAY.  ELEMS is
1190    a string where each character denotes a parameter name.  TOPNAME is
1191    the name of the top element above the elements.  */
1192 static int
1193 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1194                const char *topname, const char *elems)
1195 {
1196   gcry_sexp_t list, l2;
1197   const char *s;
1198   int i, idx;
1199   int rc = 0;
1200
1201   list = gcry_sexp_find_token (sexp, topname, 0);
1202   if (!list)
1203     return gpg_error (GPG_ERR_INV_OBJ);
1204   l2 = gcry_sexp_cadr (list);
1205   gcry_sexp_release (list);
1206   list = l2;
1207   if (!list)
1208     return gpg_error (GPG_ERR_NO_OBJ);
1209
1210   for (idx=0,s=elems; *s; s++, idx++)
1211     {
1212       l2 = gcry_sexp_find_token (list, s, 1);
1213       if (!l2)
1214         {
1215           rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1216           goto leave;
1217         }
1218       array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1219       gcry_sexp_release (l2);
1220       if (!array[idx])
1221         {
1222           rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1223           goto leave;
1224         }
1225     }
1226   gcry_sexp_release (list);
1227
1228  leave:
1229   if (rc)
1230     {
1231       for (i=0; i<idx; i++)
1232         {
1233           gcry_mpi_release (array[i]);
1234           array[i] = NULL;
1235         }
1236       gcry_sexp_release (list);
1237     }
1238   return rc;
1239 }
1240
1241
1242 /* Create a keyblock using the given KEYGRIP.  ALGO is the OpenPGP
1243    algorithm of that keygrip.  */
1244 static int
1245 do_create_from_keygrip (ctrl_t ctrl, int algo, const char *hexkeygrip,
1246                         kbnode_t pub_root, u32 timestamp, u32 expireval,
1247                         int is_subkey)
1248 {
1249   int err;
1250   PACKET *pkt;
1251   PKT_public_key *pk;
1252   gcry_sexp_t s_key;
1253   const char *algoelem;
1254
1255   if (hexkeygrip[0] == '&')
1256     hexkeygrip++;
1257
1258   switch (algo)
1259     {
1260     case PUBKEY_ALGO_RSA:       algoelem = "ne"; break;
1261     case PUBKEY_ALGO_DSA:       algoelem = "pqgy"; break;
1262     case PUBKEY_ALGO_ELGAMAL_E: algoelem = "pgy"; break;
1263     case PUBKEY_ALGO_ECDH:
1264     case PUBKEY_ALGO_ECDSA:     algoelem = ""; break;
1265     case PUBKEY_ALGO_EDDSA:     algoelem = ""; break;
1266     default: return gpg_error (GPG_ERR_INTERNAL);
1267     }
1268
1269
1270   /* Ask the agent for the public key matching HEXKEYGRIP.  */
1271   {
1272     unsigned char *public;
1273
1274     err = agent_readkey (ctrl, 0, hexkeygrip, &public);
1275     if (err)
1276       return err;
1277     err = gcry_sexp_sscan (&s_key, NULL,
1278                            public, gcry_sexp_canon_len (public, 0, NULL, NULL));
1279     xfree (public);
1280     if (err)
1281       return err;
1282   }
1283
1284   /* Build a public key packet.  */
1285   pk = xtrycalloc (1, sizeof *pk);
1286   if (!pk)
1287     {
1288       err = gpg_error_from_syserror ();
1289       gcry_sexp_release (s_key);
1290       return err;
1291     }
1292
1293   pk->timestamp = timestamp;
1294   pk->version = 4;
1295   if (expireval)
1296     pk->expiredate = pk->timestamp + expireval;
1297   pk->pubkey_algo = algo;
1298
1299   if (algo == PUBKEY_ALGO_ECDSA
1300       || algo == PUBKEY_ALGO_EDDSA
1301       || algo == PUBKEY_ALGO_ECDH )
1302     err = ecckey_from_sexp (pk->pkey, s_key, algo);
1303   else
1304     err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1305   if (err)
1306     {
1307       log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1308       gcry_sexp_release (s_key);
1309       free_public_key (pk);
1310       return err;
1311     }
1312   gcry_sexp_release (s_key);
1313
1314   pkt = xtrycalloc (1, sizeof *pkt);
1315   if (!pkt)
1316     {
1317       err = gpg_error_from_syserror ();
1318       free_public_key (pk);
1319       return err;
1320     }
1321
1322   pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1323   pkt->pkt.public_key = pk;
1324   add_kbnode (pub_root, new_kbnode (pkt));
1325
1326   return 0;
1327 }
1328
1329
1330 /* Common code for the key generation function gen_xxx.  */
1331 static int
1332 common_gen (const char *keyparms, int algo, const char *algoelem,
1333             kbnode_t pub_root, u32 timestamp, u32 expireval, int is_subkey,
1334             int keygen_flags, const char *passphrase,
1335             char **cache_nonce_addr, char **passwd_nonce_addr)
1336 {
1337   int err;
1338   PACKET *pkt;
1339   PKT_public_key *pk;
1340   gcry_sexp_t s_key;
1341
1342   err = agent_genkey (NULL, cache_nonce_addr, passwd_nonce_addr, keyparms,
1343                       !!(keygen_flags & KEYGEN_FLAG_NO_PROTECTION),
1344                       passphrase,
1345                       &s_key);
1346   if (err)
1347     {
1348       log_error ("agent_genkey failed: %s\n", gpg_strerror (err) );
1349       return err;
1350     }
1351
1352   pk = xtrycalloc (1, sizeof *pk);
1353   if (!pk)
1354     {
1355       err = gpg_error_from_syserror ();
1356       gcry_sexp_release (s_key);
1357       return err;
1358     }
1359
1360   pk->timestamp = timestamp;
1361   pk->version = 4;
1362   if (expireval)
1363     pk->expiredate = pk->timestamp + expireval;
1364   pk->pubkey_algo = algo;
1365
1366   if (algo == PUBKEY_ALGO_ECDSA
1367       || algo == PUBKEY_ALGO_EDDSA
1368       || algo == PUBKEY_ALGO_ECDH )
1369     err = ecckey_from_sexp (pk->pkey, s_key, algo);
1370   else
1371     err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1372   if (err)
1373     {
1374       log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1375       gcry_sexp_release (s_key);
1376       free_public_key (pk);
1377       return err;
1378     }
1379   gcry_sexp_release (s_key);
1380
1381   pkt = xtrycalloc (1, sizeof *pkt);
1382   if (!pkt)
1383     {
1384       err = gpg_error_from_syserror ();
1385       free_public_key (pk);
1386       return err;
1387     }
1388
1389   pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1390   pkt->pkt.public_key = pk;
1391   add_kbnode (pub_root, new_kbnode (pkt));
1392
1393   return 0;
1394 }
1395
1396
1397 /*
1398  * Generate an Elgamal key.
1399  */
1400 static int
1401 gen_elg (int algo, unsigned int nbits, KBNODE pub_root,
1402          u32 timestamp, u32 expireval, int is_subkey,
1403          int keygen_flags, const char *passphrase,
1404          char **cache_nonce_addr, char **passwd_nonce_addr)
1405 {
1406   int err;
1407   char *keyparms;
1408   char nbitsstr[35];
1409
1410   log_assert (is_ELGAMAL (algo));
1411
1412   if (nbits < 1024)
1413     {
1414       nbits = 2048;
1415       log_info (_("keysize invalid; using %u bits\n"), nbits );
1416     }
1417   else if (nbits > 4096)
1418     {
1419       nbits = 4096;
1420       log_info (_("keysize invalid; using %u bits\n"), nbits );
1421     }
1422
1423   if ((nbits % 32))
1424     {
1425       nbits = ((nbits + 31) / 32) * 32;
1426       log_info (_("keysize rounded up to %u bits\n"), nbits );
1427     }
1428
1429   /* Note that we use transient-key only if no-protection has also
1430      been enabled.  */
1431   snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1432   keyparms = xtryasprintf ("(genkey(%s(nbits %zu:%s)%s))",
1433                            algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1434                            algo == GCRY_PK_ELG   ? "elg" : "x-oops" ,
1435                            strlen (nbitsstr), nbitsstr,
1436                            ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1437                             && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1438                            "(transient-key)" : "" );
1439   if (!keyparms)
1440     err = gpg_error_from_syserror ();
1441   else
1442     {
1443       err = common_gen (keyparms, algo, "pgy",
1444                         pub_root, timestamp, expireval, is_subkey,
1445                         keygen_flags, passphrase,
1446                         cache_nonce_addr, passwd_nonce_addr);
1447       xfree (keyparms);
1448     }
1449
1450   return err;
1451 }
1452
1453
1454 /*
1455  * Generate an DSA key
1456  */
1457 static gpg_error_t
1458 gen_dsa (unsigned int nbits, KBNODE pub_root,
1459          u32 timestamp, u32 expireval, int is_subkey,
1460          int keygen_flags, const char *passphrase,
1461          char **cache_nonce_addr, char **passwd_nonce_addr)
1462 {
1463   int err;
1464   unsigned int qbits;
1465   char *keyparms;
1466   char nbitsstr[35];
1467   char qbitsstr[35];
1468
1469   if (nbits < 768)
1470     {
1471       nbits = 2048;
1472       log_info(_("keysize invalid; using %u bits\n"), nbits );
1473     }
1474   else if ( nbits > 3072 )
1475     {
1476       nbits = 3072;
1477       log_info(_("keysize invalid; using %u bits\n"), nbits );
1478     }
1479
1480   if( (nbits % 64) )
1481     {
1482       nbits = ((nbits + 63) / 64) * 64;
1483       log_info(_("keysize rounded up to %u bits\n"), nbits );
1484     }
1485
1486   /* To comply with FIPS rules we round up to the next value unless in
1487      expert mode.  */
1488   if (!opt.expert && nbits > 1024 && (nbits % 1024))
1489     {
1490       nbits = ((nbits + 1023) / 1024) * 1024;
1491       log_info(_("keysize rounded up to %u bits\n"), nbits );
1492     }
1493
1494   /*
1495     Figure out a q size based on the key size.  FIPS 180-3 says:
1496
1497     L = 1024, N = 160
1498     L = 2048, N = 224
1499     L = 2048, N = 256
1500     L = 3072, N = 256
1501
1502     2048/256 is an odd pair since there is also a 2048/224 and
1503     3072/256.  Matching sizes is not a very exact science.
1504
1505     We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1506     but less than 2048, and 160 for 1024 (DSA1).
1507   */
1508
1509   if (nbits > 2047)
1510     qbits = 256;
1511   else if ( nbits > 1024)
1512     qbits = 224;
1513   else
1514     qbits = 160;
1515
1516   if (qbits != 160 )
1517     log_info (_("WARNING: some OpenPGP programs can't"
1518                 " handle a DSA key with this digest size\n"));
1519
1520   snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1521   snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
1522   keyparms = xtryasprintf ("(genkey(dsa(nbits %zu:%s)(qbits %zu:%s)%s))",
1523                            strlen (nbitsstr), nbitsstr,
1524                            strlen (qbitsstr), qbitsstr,
1525                            ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1526                             && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1527                            "(transient-key)" : "" );
1528   if (!keyparms)
1529     err = gpg_error_from_syserror ();
1530   else
1531     {
1532       err = common_gen (keyparms, PUBKEY_ALGO_DSA, "pqgy",
1533                         pub_root, timestamp, expireval, is_subkey,
1534                         keygen_flags, passphrase,
1535                         cache_nonce_addr, passwd_nonce_addr);
1536       xfree (keyparms);
1537     }
1538
1539   return err;
1540 }
1541
1542
1543
1544 /*
1545  * Generate an ECC key
1546  */
1547 static gpg_error_t
1548 gen_ecc (int algo, const char *curve, kbnode_t pub_root,
1549          u32 timestamp, u32 expireval, int is_subkey,
1550          int keygen_flags, const char *passphrase,
1551          char **cache_nonce_addr, char **passwd_nonce_addr)
1552 {
1553   gpg_error_t err;
1554   char *keyparms;
1555
1556   log_assert (algo == PUBKEY_ALGO_ECDSA
1557               || algo == PUBKEY_ALGO_EDDSA
1558               || algo == PUBKEY_ALGO_ECDH);
1559
1560   if (!curve || !*curve)
1561     return gpg_error (GPG_ERR_UNKNOWN_CURVE);
1562
1563   /* Note that we use the "comp" flag with EdDSA to request the use of
1564      a 0x40 compression prefix octet.  */
1565   if (algo == PUBKEY_ALGO_EDDSA)
1566     keyparms = xtryasprintf
1567       ("(genkey(ecc(curve %zu:%s)(flags eddsa comp%s)))",
1568        strlen (curve), curve,
1569        (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1570          && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1571         " transient-key" : ""));
1572   else if (algo == PUBKEY_ALGO_ECDH && !strcmp (curve, "Curve25519"))
1573     keyparms = xtryasprintf
1574       ("(genkey(ecc(curve %zu:%s)(flags djb-tweak comp%s)))",
1575        strlen (curve), curve,
1576        (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1577          && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1578         " transient-key" : ""));
1579   else
1580     keyparms = xtryasprintf
1581       ("(genkey(ecc(curve %zu:%s)(flags nocomp%s)))",
1582        strlen (curve), curve,
1583        (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1584          && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1585         " transient-key" : ""));
1586
1587   if (!keyparms)
1588     err = gpg_error_from_syserror ();
1589   else
1590     {
1591       err = common_gen (keyparms, algo, "",
1592                         pub_root, timestamp, expireval, is_subkey,
1593                         keygen_flags, passphrase,
1594                         cache_nonce_addr, passwd_nonce_addr);
1595       xfree (keyparms);
1596     }
1597
1598   return err;
1599 }
1600
1601
1602 /*
1603  * Generate an RSA key.
1604  */
1605 static int
1606 gen_rsa (int algo, unsigned int nbits, KBNODE pub_root,
1607          u32 timestamp, u32 expireval, int is_subkey,
1608          int keygen_flags, const char *passphrase,
1609          char **cache_nonce_addr, char **passwd_nonce_addr)
1610 {
1611   int err;
1612   char *keyparms;
1613   char nbitsstr[35];
1614   const unsigned maxsize = (opt.flags.large_rsa ? 8192 : 4096);
1615
1616   log_assert (is_RSA(algo));
1617
1618   if (!nbits)
1619     nbits = get_keysize_range (algo, NULL, NULL);
1620
1621   if (nbits < 1024)
1622     {
1623       nbits = 2048;
1624       log_info (_("keysize invalid; using %u bits\n"), nbits );
1625     }
1626   else if (nbits > maxsize)
1627     {
1628       nbits = maxsize;
1629       log_info (_("keysize invalid; using %u bits\n"), nbits );
1630     }
1631
1632   if ((nbits % 32))
1633     {
1634       nbits = ((nbits + 31) / 32) * 32;
1635       log_info (_("keysize rounded up to %u bits\n"), nbits );
1636     }
1637
1638   snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1639   keyparms = xtryasprintf ("(genkey(rsa(nbits %zu:%s)%s))",
1640                            strlen (nbitsstr), nbitsstr,
1641                            ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1642                             && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1643                            "(transient-key)" : "" );
1644   if (!keyparms)
1645     err = gpg_error_from_syserror ();
1646   else
1647     {
1648       err = common_gen (keyparms, algo, "ne",
1649                         pub_root, timestamp, expireval, is_subkey,
1650                         keygen_flags, passphrase,
1651                         cache_nonce_addr, passwd_nonce_addr);
1652       xfree (keyparms);
1653     }
1654
1655   return err;
1656 }
1657
1658
1659 /****************
1660  * check valid days:
1661  * return 0 on error or the multiplier
1662  */
1663 static int
1664 check_valid_days( const char *s )
1665 {
1666     if( !digitp(s) )
1667         return 0;
1668     for( s++; *s; s++)
1669         if( !digitp(s) )
1670             break;
1671     if( !*s )
1672         return 1;
1673     if( s[1] )
1674         return 0; /* e.g. "2323wc" */
1675     if( *s == 'd' || *s == 'D' )
1676         return 1;
1677     if( *s == 'w' || *s == 'W' )
1678         return 7;
1679     if( *s == 'm' || *s == 'M' )
1680         return 30;
1681     if( *s == 'y' || *s == 'Y' )
1682         return 365;
1683     return 0;
1684 }
1685
1686
1687 static void
1688 print_key_flags(int flags)
1689 {
1690   if(flags&PUBKEY_USAGE_SIG)
1691     tty_printf("%s ",_("Sign"));
1692
1693   if(flags&PUBKEY_USAGE_CERT)
1694     tty_printf("%s ",_("Certify"));
1695
1696   if(flags&PUBKEY_USAGE_ENC)
1697     tty_printf("%s ",_("Encrypt"));
1698
1699   if(flags&PUBKEY_USAGE_AUTH)
1700     tty_printf("%s ",_("Authenticate"));
1701 }
1702
1703
1704 /* Ask for the key flags and return them.  CURRENT gives the current
1705  * usage which should normally be given as 0. */
1706 unsigned int
1707 ask_key_flags (int algo, int subkey, unsigned int current)
1708 {
1709   /* TRANSLATORS: Please use only plain ASCII characters for the
1710      translation.  If this is not possible use single digits.  The
1711      string needs to 8 bytes long. Here is a description of the
1712      functions:
1713
1714        s = Toggle signing capability
1715        e = Toggle encryption capability
1716        a = Toggle authentication capability
1717        q = Finish
1718   */
1719   const char *togglers = _("SsEeAaQq");
1720   char *answer = NULL;
1721   const char *s;
1722   unsigned int possible = openpgp_pk_algo_usage(algo);
1723
1724   if ( strlen(togglers) != 8 )
1725     {
1726       tty_printf ("NOTE: Bad translation at %s:%d. "
1727                   "Please report.\n", __FILE__, __LINE__);
1728       togglers = "11223300";
1729     }
1730
1731   /* Only primary keys may certify. */
1732   if(subkey)
1733     possible&=~PUBKEY_USAGE_CERT;
1734
1735   /* Preload the current set with the possible set, minus
1736      authentication if CURRENT has been given as 0.  If CURRENT has
1737      been has non-zero we mask with all possible usages. */
1738   if (current)
1739     current &= possible;
1740   else
1741     current = (possible&~PUBKEY_USAGE_AUTH);
1742
1743   for(;;)
1744     {
1745       tty_printf("\n");
1746       tty_printf(_("Possible actions for a %s key: "),
1747                  (algo == PUBKEY_ALGO_ECDSA
1748                   || algo == PUBKEY_ALGO_EDDSA)
1749                  ? "ECDSA/EdDSA" : openpgp_pk_algo_name (algo));
1750       print_key_flags(possible);
1751       tty_printf("\n");
1752       tty_printf(_("Current allowed actions: "));
1753       print_key_flags(current);
1754       tty_printf("\n\n");
1755
1756       if(possible&PUBKEY_USAGE_SIG)
1757         tty_printf(_("   (%c) Toggle the sign capability\n"),
1758                    togglers[0]);
1759       if(possible&PUBKEY_USAGE_ENC)
1760         tty_printf(_("   (%c) Toggle the encrypt capability\n"),
1761                    togglers[2]);
1762       if(possible&PUBKEY_USAGE_AUTH)
1763         tty_printf(_("   (%c) Toggle the authenticate capability\n"),
1764                    togglers[4]);
1765
1766       tty_printf(_("   (%c) Finished\n"),togglers[6]);
1767       tty_printf("\n");
1768
1769       xfree(answer);
1770       answer = cpr_get("keygen.flags",_("Your selection? "));
1771       cpr_kill_prompt();
1772
1773       if (*answer == '=')
1774         {
1775           /* Hack to allow direct entry of the capabilities.  */
1776           current = 0;
1777           for (s=answer+1; *s; s++)
1778             {
1779               if ((*s == 's' || *s == 'S') && (possible&PUBKEY_USAGE_SIG))
1780                 current |= PUBKEY_USAGE_SIG;
1781               else if ((*s == 'e' || *s == 'E') && (possible&PUBKEY_USAGE_ENC))
1782                 current |= PUBKEY_USAGE_ENC;
1783               else if ((*s == 'a' || *s == 'A') && (possible&PUBKEY_USAGE_AUTH))
1784                 current |= PUBKEY_USAGE_AUTH;
1785               else if (!subkey && *s == 'c')
1786                 {
1787                   /* Accept 'c' for the primary key because USAGE_CERT
1788                      will will be set anyway.  This is for folks who
1789                      want to experiment with a cert-only primary key.  */
1790                   current |= PUBKEY_USAGE_CERT;
1791                 }
1792             }
1793           break;
1794         }
1795       else if (strlen(answer)>1)
1796         tty_printf(_("Invalid selection.\n"));
1797       else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1798         break;
1799       else if((*answer==togglers[0] || *answer==togglers[1])
1800               && possible&PUBKEY_USAGE_SIG)
1801         {
1802           if(current&PUBKEY_USAGE_SIG)
1803             current&=~PUBKEY_USAGE_SIG;
1804           else
1805             current|=PUBKEY_USAGE_SIG;
1806         }
1807       else if((*answer==togglers[2] || *answer==togglers[3])
1808               && possible&PUBKEY_USAGE_ENC)
1809         {
1810           if(current&PUBKEY_USAGE_ENC)
1811             current&=~PUBKEY_USAGE_ENC;
1812           else
1813             current|=PUBKEY_USAGE_ENC;
1814         }
1815       else if((*answer==togglers[4] || *answer==togglers[5])
1816               && possible&PUBKEY_USAGE_AUTH)
1817         {
1818           if(current&PUBKEY_USAGE_AUTH)
1819             current&=~PUBKEY_USAGE_AUTH;
1820           else
1821             current|=PUBKEY_USAGE_AUTH;
1822         }
1823       else
1824         tty_printf(_("Invalid selection.\n"));
1825     }
1826
1827   xfree(answer);
1828
1829   return current;
1830 }
1831
1832
1833 /* Check whether we have a key for the key with HEXGRIP.  Returns 0 if
1834    there is no such key or the OpenPGP algo number for the key.  */
1835 static int
1836 check_keygrip (ctrl_t ctrl, const char *hexgrip)
1837 {
1838   gpg_error_t err;
1839   unsigned char *public;
1840   size_t publiclen;
1841   const char *algostr;
1842
1843   if (hexgrip[0] == '&')
1844     hexgrip++;
1845
1846   err = agent_readkey (ctrl, 0, hexgrip, &public);
1847   if (err)
1848     return 0;
1849   publiclen = gcry_sexp_canon_len (public, 0, NULL, NULL);
1850
1851   get_pk_algo_from_canon_sexp (public, publiclen, &algostr);
1852   xfree (public);
1853
1854   /* FIXME: Mapping of ECC algorithms is probably not correct. */
1855   if (!algostr)
1856     return 0;
1857   else if (!strcmp (algostr, "rsa"))
1858     return PUBKEY_ALGO_RSA;
1859   else if (!strcmp (algostr, "dsa"))
1860     return PUBKEY_ALGO_DSA;
1861   else if (!strcmp (algostr, "elg"))
1862     return PUBKEY_ALGO_ELGAMAL_E;
1863   else if (!strcmp (algostr, "ecc"))
1864     return PUBKEY_ALGO_ECDH;
1865   else if (!strcmp (algostr, "ecdsa"))
1866     return PUBKEY_ALGO_ECDSA;
1867   else if (!strcmp (algostr, "eddsa"))
1868     return PUBKEY_ALGO_EDDSA;
1869   else
1870     return 0;
1871 }
1872
1873
1874
1875 /* Ask for an algorithm.  The function returns the algorithm id to
1876  * create. If ADDMODE is false the function won't show an option to
1877  * create the primary and subkey combined and won't set R_USAGE
1878  * either.  If a combined algorithm has been selected, the subkey
1879  * algorithm is stored at R_SUBKEY_ALGO.  If R_KEYGRIP is given, the
1880  * user has the choice to enter the keygrip of an existing key.  That
1881  * keygrip is then stored at this address.  The caller needs to free
1882  * it. */
1883 static int
1884 ask_algo (ctrl_t ctrl, int addmode, int *r_subkey_algo, unsigned int *r_usage,
1885           char **r_keygrip)
1886 {
1887   char *keygrip = NULL;
1888   char *answer = NULL;
1889   int algo;
1890   int dummy_algo;
1891
1892   if (!r_subkey_algo)
1893     r_subkey_algo = &dummy_algo;
1894
1895   tty_printf (_("Please select what kind of key you want:\n"));
1896
1897 #if GPG_USE_RSA
1898   if (!addmode)
1899     tty_printf (_("   (%d) RSA and RSA (default)\n"), 1 );
1900 #endif
1901
1902   if (!addmode && opt.compliance != CO_DE_VS)
1903     tty_printf (_("   (%d) DSA and Elgamal\n"), 2 );
1904
1905   if (opt.compliance != CO_DE_VS)
1906     tty_printf (_("   (%d) DSA (sign only)\n"), 3 );
1907 #if GPG_USE_RSA
1908   tty_printf (_("   (%d) RSA (sign only)\n"), 4 );
1909 #endif
1910
1911   if (addmode)
1912     {
1913       if (opt.compliance != CO_DE_VS)
1914         tty_printf (_("   (%d) Elgamal (encrypt only)\n"), 5 );
1915 #if GPG_USE_RSA
1916       tty_printf (_("   (%d) RSA (encrypt only)\n"), 6 );
1917 #endif
1918     }
1919   if (opt.expert)
1920     {
1921       if (opt.compliance != CO_DE_VS)
1922         tty_printf (_("   (%d) DSA (set your own capabilities)\n"), 7 );
1923 #if GPG_USE_RSA
1924       tty_printf (_("   (%d) RSA (set your own capabilities)\n"), 8 );
1925 #endif
1926     }
1927
1928 #if GPG_USE_ECDSA || GPG_USE_ECDH || GPG_USE_EDDSA
1929   if (opt.expert && !addmode)
1930     tty_printf (_("   (%d) ECC and ECC\n"), 9 );
1931   if (opt.expert)
1932     tty_printf (_("  (%d) ECC (sign only)\n"), 10 );
1933   if (opt.expert)
1934     tty_printf (_("  (%d) ECC (set your own capabilities)\n"), 11 );
1935   if (opt.expert && addmode)
1936     tty_printf (_("  (%d) ECC (encrypt only)\n"), 12 );
1937 #endif
1938
1939   if (opt.expert && r_keygrip)
1940     tty_printf (_("  (%d) Existing key\n"), 13 );
1941
1942   for (;;)
1943     {
1944       *r_usage = 0;
1945       *r_subkey_algo = 0;
1946       xfree (answer);
1947       answer = cpr_get ("keygen.algo", _("Your selection? "));
1948       cpr_kill_prompt ();
1949       algo = *answer? atoi (answer) : 1;
1950
1951       if (opt.compliance == CO_DE_VS
1952           && (algo == 2 || algo == 3 || algo == 5 || algo == 7))
1953         {
1954           tty_printf (_("Invalid selection.\n"));
1955         }
1956       else if ((algo == 1 || !strcmp (answer, "rsa+rsa")) && !addmode)
1957         {
1958           algo = PUBKEY_ALGO_RSA;
1959           *r_subkey_algo = PUBKEY_ALGO_RSA;
1960           break;
1961         }
1962       else if ((algo == 2 || !strcmp (answer, "dsa+elg")) && !addmode)
1963         {
1964           algo = PUBKEY_ALGO_DSA;
1965           *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1966           break;
1967         }
1968       else if (algo == 3 || !strcmp (answer, "dsa"))
1969         {
1970           algo = PUBKEY_ALGO_DSA;
1971           *r_usage = PUBKEY_USAGE_SIG;
1972           break;
1973         }
1974       else if (algo == 4 || !strcmp (answer, "rsa/s"))
1975         {
1976           algo = PUBKEY_ALGO_RSA;
1977           *r_usage = PUBKEY_USAGE_SIG;
1978           break;
1979         }
1980       else if ((algo == 5 || !strcmp (answer, "elg")) && addmode)
1981         {
1982           algo = PUBKEY_ALGO_ELGAMAL_E;
1983           *r_usage = PUBKEY_USAGE_ENC;
1984           break;
1985         }
1986       else if ((algo == 6 || !strcmp (answer, "rsa/e")) && addmode)
1987         {
1988           algo = PUBKEY_ALGO_RSA;
1989           *r_usage = PUBKEY_USAGE_ENC;
1990           break;
1991         }
1992       else if ((algo == 7 || !strcmp (answer, "dsa/*")) && opt.expert)
1993         {
1994           algo = PUBKEY_ALGO_DSA;
1995           *r_usage = ask_key_flags (algo, addmode, 0);
1996           break;
1997         }
1998       else if ((algo == 8 || !strcmp (answer, "rsa/*")) && opt.expert)
1999         {
2000           algo = PUBKEY_ALGO_RSA;
2001           *r_usage = ask_key_flags (algo, addmode, 0);
2002           break;
2003         }
2004       else if ((algo == 9 || !strcmp (answer, "ecc+ecc"))
2005                && opt.expert && !addmode)
2006         {
2007           algo = PUBKEY_ALGO_ECDSA;
2008           *r_subkey_algo = PUBKEY_ALGO_ECDH;
2009           break;
2010         }
2011       else if ((algo == 10 || !strcmp (answer, "ecc/s")) && opt.expert)
2012         {
2013           algo = PUBKEY_ALGO_ECDSA;
2014           *r_usage = PUBKEY_USAGE_SIG;
2015           break;
2016         }
2017       else if ((algo == 11 || !strcmp (answer, "ecc/*")) && opt.expert)
2018         {
2019           algo = PUBKEY_ALGO_ECDSA;
2020           *r_usage = ask_key_flags (algo, addmode, 0);
2021           break;
2022         }
2023       else if ((algo == 12 || !strcmp (answer, "ecc/e"))
2024                && opt.expert && addmode)
2025         {
2026           algo = PUBKEY_ALGO_ECDH;
2027           *r_usage = PUBKEY_USAGE_ENC;
2028           break;
2029         }
2030       else if ((algo == 13 || !strcmp (answer, "keygrip"))
2031                && opt.expert && r_keygrip)
2032         {
2033           for (;;)
2034             {
2035               xfree (answer);
2036               answer = tty_get (_("Enter the keygrip: "));
2037               tty_kill_prompt ();
2038               trim_spaces (answer);
2039               if (!*answer)
2040                 {
2041                   xfree (answer);
2042                   answer = NULL;
2043                   continue;
2044                 }
2045
2046               if (strlen (answer) != 40 &&
2047                        !(answer[0] == '&' && strlen (answer+1) == 40))
2048                 tty_printf
2049                   (_("Not a valid keygrip (expecting 40 hex digits)\n"));
2050               else if (!(algo = check_keygrip (ctrl, answer)) )
2051                 tty_printf (_("No key with this keygrip\n"));
2052               else
2053                 break; /* Okay.  */
2054             }
2055           xfree (keygrip);
2056           keygrip = answer;
2057           answer = NULL;
2058           *r_usage = ask_key_flags (algo, addmode, 0);
2059           break;
2060         }
2061       else
2062         tty_printf (_("Invalid selection.\n"));
2063
2064     }
2065
2066   xfree(answer);
2067   if (r_keygrip)
2068     *r_keygrip = keygrip;
2069   return algo;
2070 }
2071
2072
2073 static unsigned int
2074 get_keysize_range (int algo, unsigned int *min, unsigned int *max)
2075 {
2076   unsigned int def;
2077   unsigned int dummy1, dummy2;
2078
2079   if (!min)
2080     min = &dummy1;
2081   if (!max)
2082     max = &dummy2;
2083
2084   switch(algo)
2085     {
2086     case PUBKEY_ALGO_DSA:
2087       *min = opt.expert? 768 : 1024;
2088       *max=3072;
2089       def=2048;
2090       break;
2091
2092     case PUBKEY_ALGO_ECDSA:
2093     case PUBKEY_ALGO_ECDH:
2094       *min=256;
2095       *max=521;
2096       def=256;
2097       break;
2098
2099     case PUBKEY_ALGO_EDDSA:
2100       *min=255;
2101       *max=441;
2102       def=255;
2103       break;
2104
2105     default:
2106       *min = opt.compliance == CO_DE_VS ? 2048: 1024;
2107       *max = 4096;
2108       def = 2048;
2109       break;
2110     }
2111
2112   return def;
2113 }
2114
2115
2116 /* Return a fixed up keysize depending on ALGO.  */
2117 static unsigned int
2118 fixup_keysize (unsigned int nbits, int algo, int silent)
2119 {
2120   if (algo == PUBKEY_ALGO_DSA && (nbits % 64))
2121     {
2122       nbits = ((nbits + 63) / 64) * 64;
2123       if (!silent)
2124         tty_printf (_("rounded up to %u bits\n"), nbits);
2125     }
2126   else if (algo == PUBKEY_ALGO_EDDSA)
2127     {
2128       if (nbits != 255 && nbits != 441)
2129         {
2130           if (nbits < 256)
2131             nbits = 255;
2132           else
2133             nbits = 441;
2134           if (!silent)
2135             tty_printf (_("rounded to %u bits\n"), nbits);
2136         }
2137     }
2138   else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2139     {
2140       if (nbits != 256 && nbits != 384 && nbits != 521)
2141         {
2142           if (nbits < 256)
2143             nbits = 256;
2144           else if (nbits < 384)
2145             nbits = 384;
2146           else
2147             nbits = 521;
2148           if (!silent)
2149             tty_printf (_("rounded to %u bits\n"), nbits);
2150         }
2151     }
2152   else if ((nbits % 32))
2153     {
2154       nbits = ((nbits + 31) / 32) * 32;
2155       if (!silent)
2156         tty_printf (_("rounded up to %u bits\n"), nbits );
2157     }
2158
2159   return nbits;
2160 }
2161
2162
2163 /* Ask for the key size.  ALGO is the algorithm.  If PRIMARY_KEYSIZE
2164    is not 0, the function asks for the size of the encryption
2165    subkey. */
2166 static unsigned
2167 ask_keysize (int algo, unsigned int primary_keysize)
2168 {
2169   unsigned int nbits;
2170   unsigned int min, def, max;
2171   int for_subkey = !!primary_keysize;
2172   int autocomp = 0;
2173
2174   def = get_keysize_range (algo, &min, &max);
2175
2176   if (primary_keysize && !opt.expert)
2177     {
2178       /* Deduce the subkey size from the primary key size.  */
2179       if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
2180         nbits = 3072; /* For performance reasons we don't support more
2181                          than 3072 bit DSA.  However we won't see this
2182                          case anyway because DSA can't be used as an
2183                          encryption subkey ;-). */
2184       else
2185         nbits = primary_keysize;
2186       autocomp = 1;
2187       goto leave;
2188     }
2189
2190   tty_printf(_("%s keys may be between %u and %u bits long.\n"),
2191              openpgp_pk_algo_name (algo), min, max);
2192
2193   for (;;)
2194     {
2195       char *prompt, *answer;
2196
2197       if (for_subkey)
2198         prompt = xasprintf (_("What keysize do you want "
2199                               "for the subkey? (%u) "), def);
2200       else
2201         prompt = xasprintf (_("What keysize do you want? (%u) "), def);
2202       answer = cpr_get ("keygen.size", prompt);
2203       cpr_kill_prompt ();
2204       nbits = *answer? atoi (answer): def;
2205       xfree(prompt);
2206       xfree(answer);
2207
2208       if(nbits<min || nbits>max)
2209         tty_printf(_("%s keysizes must be in the range %u-%u\n"),
2210                    openpgp_pk_algo_name (algo), min, max);
2211       else
2212         break;
2213     }
2214
2215   tty_printf (_("Requested keysize is %u bits\n"), nbits);
2216
2217  leave:
2218   nbits = fixup_keysize (nbits, algo, autocomp);
2219   return nbits;
2220 }
2221
2222
2223 /* Ask for the curve.  ALGO is the selected algorithm which this
2224    function may adjust.  Returns a malloced string with the name of
2225    the curve.  BOTH tells that gpg creates a primary and subkey. */
2226 static char *
2227 ask_curve (int *algo, int *subkey_algo)
2228 {
2229   /* NB: We always use a complete algo list so that we have stable
2230      numbers in the menu regardless on how Gpg was configured.  */
2231   struct {
2232     const char *name;
2233     const char* eddsa_curve; /* Corresponding EdDSA curve.  */
2234     const char *pretty_name;
2235     unsigned int supported : 1;   /* Supported by gpg.     */
2236     unsigned int de_vs : 1;       /* Allowed in CO_DE_VS.  */
2237     unsigned int expert_only : 1; /* Only with --expert    */
2238     unsigned int available : 1;   /* Available in Libycrypt (runtime checked) */
2239   } curves[] = {
2240 #if GPG_USE_ECDSA || GPG_USE_ECDH
2241 # define MY_USE_ECDSADH 1
2242 #else
2243 # define MY_USE_ECDSADH 0
2244 #endif
2245     { "Curve25519",      "Ed25519", "Curve 25519", !!GPG_USE_EDDSA, 0, 0, 0 },
2246     { "Curve448",        "Ed448",   "Curve 448",   0/*reserved*/  , 0, 1, 0 },
2247     { "NIST P-256",      NULL, NULL,               MY_USE_ECDSADH,  0, 1, 0 },
2248     { "NIST P-384",      NULL, NULL,               MY_USE_ECDSADH,  0, 0, 0 },
2249     { "NIST P-521",      NULL, NULL,               MY_USE_ECDSADH,  0, 1, 0 },
2250     { "brainpoolP256r1", NULL, "Brainpool P-256",  MY_USE_ECDSADH,  1, 1, 0 },
2251     { "brainpoolP384r1", NULL, "Brainpool P-384",  MY_USE_ECDSADH,  1, 1, 0 },
2252     { "brainpoolP512r1", NULL, "Brainpool P-512",  MY_USE_ECDSADH,  1, 1, 0 },
2253     { "secp256k1",       NULL, NULL,               MY_USE_ECDSADH,  0, 1, 0 },
2254   };
2255 #undef MY_USE_ECDSADH
2256   int idx;
2257   char *answer;
2258   char *result = NULL;
2259   gcry_sexp_t keyparms;
2260
2261   tty_printf (_("Please select which elliptic curve you want:\n"));
2262
2263   keyparms = NULL;
2264   for (idx=0; idx < DIM(curves); idx++)
2265     {
2266       int rc;
2267
2268       curves[idx].available = 0;
2269       if (!curves[idx].supported)
2270         continue;
2271
2272       if (opt.compliance==CO_DE_VS)
2273         {
2274           if (!curves[idx].de_vs)
2275             continue; /* Not allowed.  */
2276         }
2277       else if (!opt.expert && curves[idx].expert_only)
2278         continue;
2279
2280       /* We need to switch from the ECDH name of the curve to the
2281          EDDSA name of the curve if we want a signing key.  */
2282       gcry_sexp_release (keyparms);
2283       rc = gcry_sexp_build (&keyparms, NULL,
2284                             "(public-key(ecc(curve %s)))",
2285                             curves[idx].eddsa_curve? curves[idx].eddsa_curve
2286                             /**/                   : curves[idx].name);
2287       if (rc)
2288         continue;
2289       if (!gcry_pk_get_curve (keyparms, 0, NULL))
2290         continue;
2291       if (subkey_algo && curves[idx].eddsa_curve)
2292         {
2293           /* Both Curve 25519 (or 448) keys are to be created.  Check that
2294              Libgcrypt also supports the real Curve25519 (or 448).  */
2295           gcry_sexp_release (keyparms);
2296           rc = gcry_sexp_build (&keyparms, NULL,
2297                                 "(public-key(ecc(curve %s)))",
2298                                  curves[idx].name);
2299           if (rc)
2300             continue;
2301           if (!gcry_pk_get_curve (keyparms, 0, NULL))
2302             continue;
2303         }
2304
2305       curves[idx].available = 1;
2306       tty_printf ("   (%d) %s\n", idx + 1,
2307                   curves[idx].pretty_name?
2308                   curves[idx].pretty_name:curves[idx].name);
2309     }
2310   gcry_sexp_release (keyparms);
2311
2312
2313   for (;;)
2314     {
2315       answer = cpr_get ("keygen.curve", _("Your selection? "));
2316       cpr_kill_prompt ();
2317       idx = *answer? atoi (answer) : 1;
2318       if (*answer && !idx)
2319         {
2320           /* See whether the user entered the name of the curve.  */
2321           for (idx=0; idx < DIM(curves); idx++)
2322             {
2323               if (!opt.expert && curves[idx].expert_only)
2324                 continue;
2325               if (!stricmp (curves[idx].name, answer)
2326                   || (curves[idx].pretty_name
2327                       && !stricmp (curves[idx].pretty_name, answer)))
2328                 break;
2329             }
2330           if (idx == DIM(curves))
2331             idx = -1;
2332         }
2333       else
2334         idx--;
2335       xfree(answer);
2336       answer = NULL;
2337       if (idx < 0 || idx >= DIM (curves) || !curves[idx].available)
2338         tty_printf (_("Invalid selection.\n"));
2339       else
2340         {
2341           /* If the user selected a signing algorithm and Curve25519
2342              we need to set the algo to EdDSA and update the curve name. */
2343           if ((*algo == PUBKEY_ALGO_ECDSA || *algo == PUBKEY_ALGO_EDDSA)
2344               && curves[idx].eddsa_curve)
2345             {
2346               if (subkey_algo && *subkey_algo == PUBKEY_ALGO_ECDSA)
2347                 *subkey_algo = PUBKEY_ALGO_EDDSA;
2348               *algo = PUBKEY_ALGO_EDDSA;
2349               result = xstrdup (curves[idx].eddsa_curve);
2350             }
2351           else
2352             result = xstrdup (curves[idx].name);
2353           break;
2354         }
2355     }
2356
2357   if (!result)
2358     result = xstrdup (curves[0].name);
2359
2360   return result;
2361 }
2362
2363
2364 /****************
2365  * Parse an expire string and return its value in seconds.
2366  * Returns (u32)-1 on error.
2367  * This isn't perfect since scan_isodatestr returns unix time, and
2368  * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
2369  * Because of this, we only permit setting expirations up to 2106, but
2370  * OpenPGP could theoretically allow up to 2242.  I think we'll all
2371  * just cope for the next few years until we get a 64-bit time_t or
2372  * similar.
2373  */
2374 u32
2375 parse_expire_string( const char *string )
2376 {
2377   int mult;
2378   u32 seconds;
2379   u32 abs_date = 0;
2380   u32 curtime = make_timestamp ();
2381   time_t tt;
2382
2383   if (!string || !*string || !strcmp (string, "none")
2384       || !strcmp (string, "never") || !strcmp (string, "-"))
2385     seconds = 0;
2386   else if (!strncmp (string, "seconds=", 8))
2387     seconds = atoi (string+8);
2388   else if ((abs_date = scan_isodatestr(string))
2389            && (abs_date+86400/2) > curtime)
2390     seconds = (abs_date+86400/2) - curtime;
2391   else if ((tt = isotime2epoch (string)) != (time_t)(-1))
2392     seconds = (u32)tt - curtime;
2393   else if ((mult = check_valid_days (string)))
2394     seconds = atoi (string) * 86400L * mult;
2395   else
2396     seconds = (u32)(-1);
2397
2398   return seconds;
2399 }
2400
2401 /* Parse a Creation-Date string which is either "1986-04-26" or
2402    "19860426T042640".  Returns 0 on error. */
2403 static u32
2404 parse_creation_string (const char *string)
2405 {
2406   u32 seconds;
2407
2408   if (!*string)
2409     seconds = 0;
2410   else if ( !strncmp (string, "seconds=", 8) )
2411     seconds = atoi (string+8);
2412   else if ( !(seconds = scan_isodatestr (string)))
2413     {
2414       time_t tmp = isotime2epoch (string);
2415       seconds = (tmp == (time_t)(-1))? 0 : tmp;
2416     }
2417   return seconds;
2418 }
2419
2420
2421 /* object == 0 for a key, and 1 for a sig */
2422 u32
2423 ask_expire_interval(int object,const char *def_expire)
2424 {
2425     u32 interval;
2426     char *answer;
2427
2428     switch(object)
2429       {
2430       case 0:
2431         if(def_expire)
2432           BUG();
2433         tty_printf(_("Please specify how long the key should be valid.\n"
2434                      "         0 = key does not expire\n"
2435                      "      <n>  = key expires in n days\n"
2436                      "      <n>w = key expires in n weeks\n"
2437                      "      <n>m = key expires in n months\n"
2438                      "      <n>y = key expires in n years\n"));
2439         break;
2440
2441       case 1:
2442         if(!def_expire)
2443           BUG();
2444         tty_printf(_("Please specify how long the signature should be valid.\n"
2445                      "         0 = signature does not expire\n"
2446                      "      <n>  = signature expires in n days\n"
2447                      "      <n>w = signature expires in n weeks\n"
2448                      "      <n>m = signature expires in n months\n"
2449                      "      <n>y = signature expires in n years\n"));
2450         break;
2451
2452       default:
2453         BUG();
2454       }
2455
2456     /* Note: The elgamal subkey for DSA has no expiration date because
2457      * it must be signed with the DSA key and this one has the expiration
2458      * date */
2459
2460     answer = NULL;
2461     for(;;)
2462       {
2463         u32 curtime;
2464
2465         xfree(answer);
2466         if(object==0)
2467           answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
2468         else
2469           {
2470             char *prompt;
2471
2472             prompt = xasprintf (_("Signature is valid for? (%s) "), def_expire);
2473             answer = cpr_get("siggen.valid",prompt);
2474             xfree(prompt);
2475
2476             if(*answer=='\0')
2477               answer=xstrdup(def_expire);
2478           }
2479         cpr_kill_prompt();
2480         trim_spaces(answer);
2481         curtime = make_timestamp ();
2482         interval = parse_expire_string( answer );
2483         if( interval == (u32)-1 )
2484           {
2485             tty_printf(_("invalid value\n"));
2486             continue;
2487           }
2488
2489         if( !interval )
2490           {
2491             tty_printf((object==0)
2492                        ? _("Key does not expire at all\n")
2493                        : _("Signature does not expire at all\n"));
2494           }
2495         else
2496           {
2497             tty_printf(object==0
2498                        ? _("Key expires at %s\n")
2499                        : _("Signature expires at %s\n"),
2500                        asctimestamp((ulong)(curtime + interval) ) );
2501 #if SIZEOF_TIME_T <= 4 && !defined (HAVE_UNSIGNED_TIME_T)
2502             if ( (time_t)((ulong)(curtime+interval)) < 0 )
2503               tty_printf (_("Your system can't display dates beyond 2038.\n"
2504                             "However, it will be correctly handled up to"
2505                             " 2106.\n"));
2506             else
2507 #endif /*SIZEOF_TIME_T*/
2508               if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
2509                 {
2510                   tty_printf (_("invalid value\n"));
2511                   continue;
2512                 }
2513           }
2514
2515         if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2516                                                    _("Is this correct? (y/N) ")) )
2517           break;
2518       }
2519
2520     xfree(answer);
2521     return interval;
2522 }
2523
2524 u32
2525 ask_expiredate()
2526 {
2527     u32 x = ask_expire_interval(0,NULL);
2528     return x? make_timestamp() + x : 0;
2529 }
2530
2531
2532
2533 static PKT_user_id *
2534 uid_from_string (const char *string)
2535 {
2536   size_t n;
2537   PKT_user_id *uid;
2538
2539   n = strlen (string);
2540   uid = xmalloc_clear (sizeof *uid + n);
2541   uid->len = n;
2542   strcpy (uid->name, string);
2543   uid->ref = 1;
2544   return uid;
2545 }
2546
2547
2548 /* Return true if the user id UID already exists in the keyblock.  */
2549 static int
2550 uid_already_in_keyblock (kbnode_t keyblock, const char *uid)
2551 {
2552   PKT_user_id *uidpkt = uid_from_string (uid);
2553   kbnode_t node;
2554   int result = 0;
2555
2556   for (node=keyblock; node && !result; node=node->next)
2557     if (!is_deleted_kbnode (node)
2558         && node->pkt->pkttype == PKT_USER_ID
2559         && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
2560       result = 1;
2561   free_user_id (uidpkt);
2562   return result;
2563 }
2564
2565
2566 /* Ask for a user ID.  With a MODE of 1 an extra help prompt is
2567    printed for use during a new key creation.  If KEYBLOCK is not NULL
2568    the function prevents the creation of an already existing user
2569    ID.  IF FULL is not set some prompts are not shown.  */
2570 static char *
2571 ask_user_id (int mode, int full, KBNODE keyblock)
2572 {
2573     char *answer;
2574     char *aname, *acomment, *amail, *uid;
2575
2576     if ( !mode )
2577       {
2578         /* TRANSLATORS: This is the new string telling the user what
2579            gpg is now going to do (i.e. ask for the parts of the user
2580            ID).  Note that if you do not translate this string, a
2581            different string will be used, which might still have
2582            a correct translation.  */
2583         const char *s1 =
2584           N_("\n"
2585              "GnuPG needs to construct a user ID to identify your key.\n"
2586              "\n");
2587         const char *s2 = _(s1);
2588
2589         if (!strcmp (s1, s2))
2590           {
2591             /* There is no translation for the string thus we to use
2592                the old info text.  gettext has no way to tell whether
2593                a translation is actually available, thus we need to
2594                to compare again. */
2595             /* TRANSLATORS: This string is in general not anymore used
2596                but you should keep your existing translation.  In case
2597                the new string is not translated this old string will
2598                be used. */
2599             const char *s3 = N_("\n"
2600 "You need a user ID to identify your key; "
2601                                         "the software constructs the user ID\n"
2602 "from the Real Name, Comment and Email Address in this form:\n"
2603 "    \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2604             const char *s4 = _(s3);
2605             if (strcmp (s3, s4))
2606               s2 = s3; /* A translation exists - use it. */
2607           }
2608         tty_printf ("%s", s2) ;
2609       }
2610     uid = aname = acomment = amail = NULL;
2611     for(;;) {
2612         char *p;
2613         int fail=0;
2614
2615         if( !aname ) {
2616             for(;;) {
2617                 xfree(aname);
2618                 aname = cpr_get("keygen.name",_("Real name: "));
2619                 trim_spaces(aname);
2620                 cpr_kill_prompt();
2621
2622                 if( opt.allow_freeform_uid )
2623                     break;
2624
2625                 if( strpbrk( aname, "<>" ) )
2626                   {
2627                     tty_printf(_("Invalid character in name\n"));
2628                     tty_printf(_("The characters '%s' and '%s' may not "
2629                                  "appear in name\n"), "<", ">");
2630                   }
2631                 else if( digitp(aname) )
2632                     tty_printf(_("Name may not start with a digit\n"));
2633                 else if (*aname && strlen (aname) < 5)
2634                   {
2635                     tty_printf(_("Name must be at least 5 characters long\n"));
2636                     /* However, we allow an empty name.  */
2637                   }
2638                 else
2639                     break;
2640             }
2641         }
2642         if( !amail ) {
2643             for(;;) {
2644                 xfree(amail);
2645                 amail = cpr_get("keygen.email",_("Email address: "));
2646                 trim_spaces(amail);
2647                 cpr_kill_prompt();
2648                 if( !*amail || opt.allow_freeform_uid )
2649                     break;   /* no email address is okay */
2650                 else if ( !is_valid_mailbox (amail) )
2651                     tty_printf(_("Not a valid email address\n"));
2652                 else
2653                     break;
2654             }
2655         }
2656         if (!acomment) {
2657           if (full) {
2658             for(;;) {
2659                 xfree(acomment);
2660                 acomment = cpr_get("keygen.comment",_("Comment: "));
2661                 trim_spaces(acomment);
2662                 cpr_kill_prompt();
2663                 if( !*acomment )
2664                     break;   /* no comment is okay */
2665                 else if( strpbrk( acomment, "()" ) )
2666                     tty_printf(_("Invalid character in comment\n"));
2667                 else
2668                     break;
2669             }
2670           }
2671           else {
2672             xfree (acomment);
2673             acomment = xstrdup ("");
2674           }
2675         }
2676
2677
2678         xfree(uid);
2679         uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2680         if (!*aname && *amail && !*acomment && !random_is_faked ())
2681           { /* Empty name and comment but with mail address.  Use
2682                simplified form with only the non-angle-bracketed mail
2683                address.  */
2684             p = stpcpy (p, amail);
2685           }
2686         else
2687           {
2688             p = stpcpy (p, aname );
2689             if (*acomment)
2690               p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2691             if (*amail)
2692               p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2693           }
2694
2695         /* Append a warning if the RNG is switched into fake mode.  */
2696         if ( random_is_faked ()  )
2697           strcpy(p, " (insecure!)" );
2698
2699         /* print a note in case that UTF8 mapping has to be done */
2700         for(p=uid; *p; p++ ) {
2701             if( *p & 0x80 ) {
2702                 tty_printf(_("You are using the '%s' character set.\n"),
2703                            get_native_charset() );
2704                 break;
2705             }
2706         }
2707
2708         tty_printf(_("You selected this USER-ID:\n    \"%s\"\n\n"), uid);
2709
2710         if( !*amail && !opt.allow_freeform_uid
2711             && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2712             fail = 1;
2713             tty_printf(_("Please don't put the email address "
2714                          "into the real name or the comment\n") );
2715         }
2716
2717         if (!fail && keyblock)
2718           {
2719             if (uid_already_in_keyblock (keyblock, uid))
2720               {
2721                 tty_printf (_("Such a user ID already exists on this key!\n"));
2722                 fail = 1;
2723               }
2724           }
2725
2726         for(;;) {
2727             /* TRANSLATORS: These are the allowed answers in
2728                lower and uppercase.  Below you will find the matching
2729                string which should be translated accordingly and the
2730                letter changed to match the one in the answer string.
2731
2732                  n = Change name
2733                  c = Change comment
2734                  e = Change email
2735                  o = Okay (ready, continue)
2736                  q = Quit
2737              */
2738             const char *ansstr = _("NnCcEeOoQq");
2739
2740             if( strlen(ansstr) != 10 )
2741                 BUG();
2742             if( cpr_enabled() ) {
2743                 answer = xstrdup (ansstr + (fail?8:6));
2744                 answer[1] = 0;
2745             }
2746             else if (full) {
2747                 answer = cpr_get("keygen.userid.cmd", fail?
2748                   _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2749                   _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2750                 cpr_kill_prompt();
2751             }
2752             else {
2753                 answer = cpr_get("keygen.userid.cmd", fail?
2754                   _("Change (N)ame, (E)mail, or (Q)uit? ") :
2755                   _("Change (N)ame, (E)mail, or (O)kay/(Q)uit? "));
2756                 cpr_kill_prompt();
2757             }
2758             if( strlen(answer) > 1 )
2759                 ;
2760             else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2761                 xfree(aname); aname = NULL;
2762                 break;
2763             }
2764             else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2765                 xfree(acomment); acomment = NULL;
2766                 break;
2767             }
2768             else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2769                 xfree(amail); amail = NULL;
2770                 break;
2771             }
2772             else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2773                 if( fail ) {
2774                     tty_printf(_("Please correct the error first\n"));
2775                 }
2776                 else {
2777                     xfree(aname); aname = NULL;
2778                     xfree(acomment); acomment = NULL;
2779                     xfree(amail); amail = NULL;
2780                     break;
2781                 }
2782             }
2783             else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2784                 xfree(aname); aname = NULL;
2785                 xfree(acomment); acomment = NULL;
2786                 xfree(amail); amail = NULL;
2787                 xfree(uid); uid = NULL;
2788                 break;
2789             }
2790             xfree(answer);
2791         }
2792         xfree(answer);
2793         if (!amail && !acomment)
2794             break;
2795         xfree(uid); uid = NULL;
2796     }
2797     if( uid ) {
2798         char *p = native_to_utf8( uid );
2799         xfree( uid );
2800         uid = p;
2801     }
2802     return uid;
2803 }
2804
2805
2806 /* Basic key generation.  Here we divert to the actual generation
2807    routines based on the requested algorithm.  */
2808 static int
2809 do_create (int algo, unsigned int nbits, const char *curve, KBNODE pub_root,
2810            u32 timestamp, u32 expiredate, int is_subkey,
2811            int keygen_flags, const char *passphrase,
2812            char **cache_nonce_addr, char **passwd_nonce_addr)
2813 {
2814   gpg_error_t err;
2815
2816   /* Fixme: The entropy collecting message should be moved to a
2817      libgcrypt progress handler.  */
2818   if (!opt.batch)
2819     tty_printf (_(
2820 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2821 "some other action (type on the keyboard, move the mouse, utilize the\n"
2822 "disks) during the prime generation; this gives the random number\n"
2823 "generator a better chance to gain enough entropy.\n") );
2824
2825   if (algo == PUBKEY_ALGO_ELGAMAL_E)
2826     err = gen_elg (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2827                    keygen_flags, passphrase,
2828                    cache_nonce_addr, passwd_nonce_addr);
2829   else if (algo == PUBKEY_ALGO_DSA)
2830     err = gen_dsa (nbits, pub_root, timestamp, expiredate, is_subkey,
2831                    keygen_flags, passphrase,
2832                    cache_nonce_addr, passwd_nonce_addr);
2833   else if (algo == PUBKEY_ALGO_ECDSA
2834            || algo == PUBKEY_ALGO_EDDSA
2835            || algo == PUBKEY_ALGO_ECDH)
2836     err = gen_ecc (algo, curve, pub_root, timestamp, expiredate, is_subkey,
2837                    keygen_flags, passphrase,
2838                    cache_nonce_addr, passwd_nonce_addr);
2839   else if (algo == PUBKEY_ALGO_RSA)
2840     err = gen_rsa (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2841                    keygen_flags, passphrase,
2842                    cache_nonce_addr, passwd_nonce_addr);
2843   else
2844     BUG();
2845
2846   return err;
2847 }
2848
2849
2850 /* Generate a new user id packet or return NULL if canceled.  If
2851    KEYBLOCK is not NULL the function prevents the creation of an
2852    already existing user ID.  If UIDSTR is not NULL the user is not
2853    asked but UIDSTR is used to create the user id packet; if the user
2854    id already exists NULL is returned.  UIDSTR is expected to be utf-8
2855    encoded and should have already been checked for a valid length
2856    etc.  */
2857 PKT_user_id *
2858 generate_user_id (KBNODE keyblock, const char *uidstr)
2859 {
2860   PKT_user_id *uid;
2861   char *p;
2862
2863   if (uidstr)
2864     {
2865       if (uid_already_in_keyblock (keyblock, uidstr))
2866         return NULL;  /* Already exists.  */
2867       uid = uid_from_string (uidstr);
2868     }
2869   else
2870     {
2871       p = ask_user_id (1, 1, keyblock);
2872       if (!p)
2873         return NULL;  /* Canceled. */
2874       uid = uid_from_string (p);
2875       xfree (p);
2876     }
2877   return uid;
2878 }
2879
2880
2881 /* Helper for parse_key_parameter_string for one part of the
2882  * specification string; i.e.  ALGO/FLAGS.  If STRING is NULL or empty
2883  * success is returned.  On error an error code is returned.  Note
2884  * that STRING may be modified by this function.  NULL may be passed
2885  * for any parameter.  FOR_SUBKEY shall be true if this is used as a
2886  * subkey.  */
2887 static gpg_error_t
2888 parse_key_parameter_part (char *string, int for_subkey,
2889                           int *r_algo, unsigned int *r_size,
2890                           unsigned int *r_keyuse,
2891                           char const **r_curve)
2892 {
2893   char *flags;
2894   int algo;
2895   char *endp;
2896   const char *curve = NULL;
2897   int ecdh_or_ecdsa = 0;
2898   unsigned int size;
2899   int keyuse;
2900   int i;
2901   const char *s;
2902
2903   if (!string || !*string)
2904     return 0; /* Success.  */
2905
2906   flags = strchr (string, '/');
2907   if (flags)
2908     *flags++ = 0;
2909
2910   algo = 0;
2911   if (strlen (string) >= 3 && (digitp (string+3) || !string[3]))
2912     {
2913       if (!ascii_memcasecmp (string, "rsa", 3))
2914         algo = PUBKEY_ALGO_RSA;
2915       else if (!ascii_memcasecmp (string, "dsa", 3))
2916         algo = PUBKEY_ALGO_DSA;
2917       else if (!ascii_memcasecmp (string, "elg", 3))
2918         algo = PUBKEY_ALGO_ELGAMAL_E;
2919     }
2920   if (algo)
2921     {
2922       if (!string[3])
2923         size = get_keysize_range (algo, NULL, NULL);
2924       else
2925         {
2926           size = strtoul (string+3, &endp, 10);
2927           if (size < 512 || size > 16384 || *endp)
2928             return gpg_error (GPG_ERR_INV_VALUE);
2929         }
2930     }
2931   else if ((curve = openpgp_is_curve_supported (string, &algo, &size)))
2932     {
2933       if (!algo)
2934         {
2935           algo = PUBKEY_ALGO_ECDH; /* Default ECC algorithm.  */
2936           ecdh_or_ecdsa = 1;       /* We may need to switch the algo.  */
2937         }
2938     }
2939   else
2940     return gpg_error (GPG_ERR_UNKNOWN_CURVE);
2941
2942   /* Parse the flags.  */
2943   keyuse = 0;
2944   if (flags)
2945     {
2946       char **tokens = NULL;
2947
2948       tokens = strtokenize (flags, ",");
2949       if (!tokens)
2950         return gpg_error_from_syserror ();
2951
2952       for (i=0; (s = tokens[i]); i++)
2953         {
2954           if (!*s)
2955             ;
2956           else if (!ascii_strcasecmp (s, "sign"))
2957             keyuse |= PUBKEY_USAGE_SIG;
2958           else if (!ascii_strcasecmp (s, "encrypt")
2959                    || !ascii_strcasecmp (s, "encr"))
2960             keyuse |= PUBKEY_USAGE_ENC;
2961           else if (!ascii_strcasecmp (s, "auth"))
2962             keyuse |= PUBKEY_USAGE_AUTH;
2963           else if (!ascii_strcasecmp (s, "cert"))
2964             keyuse |= PUBKEY_USAGE_CERT;
2965           else if (!ascii_strcasecmp (s, "ecdsa"))
2966             {
2967               if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2968                 algo = PUBKEY_ALGO_ECDSA;
2969               else
2970                 {
2971                   xfree (tokens);
2972                   return gpg_error (GPG_ERR_INV_FLAG);
2973                 }
2974               ecdh_or_ecdsa = 0;
2975             }
2976           else if (!ascii_strcasecmp (s, "ecdh"))
2977             {
2978               if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2979                 algo = PUBKEY_ALGO_ECDH;
2980               else
2981                 {
2982                   xfree (tokens);
2983                   return gpg_error (GPG_ERR_INV_FLAG);
2984                 }
2985               ecdh_or_ecdsa = 0;
2986             }
2987           else if (!ascii_strcasecmp (s, "eddsa"))
2988             {
2989               /* Not required but we allow it for consistency.  */
2990               if (algo == PUBKEY_ALGO_EDDSA)
2991                 ;
2992               else
2993                 {
2994                   xfree (tokens);
2995                   return gpg_error (GPG_ERR_INV_FLAG);
2996                 }
2997             }
2998           else
2999             {
3000               xfree (tokens);
3001               return gpg_error (GPG_ERR_UNKNOWN_FLAG);
3002             }
3003         }
3004
3005       xfree (tokens);
3006     }
3007
3008   /* If not yet decided switch between ecdh and ecdsa.  */
3009   if (ecdh_or_ecdsa && keyuse)
3010     algo = (keyuse & PUBKEY_USAGE_ENC)? PUBKEY_ALGO_ECDH : PUBKEY_ALGO_ECDSA;
3011   else if (ecdh_or_ecdsa)
3012     algo = for_subkey? PUBKEY_ALGO_ECDH : PUBKEY_ALGO_ECDSA;
3013
3014   /* Set or fix key usage.  */
3015   if (!keyuse)
3016     {
3017       if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA
3018           || algo == PUBKEY_ALGO_DSA)
3019         keyuse = PUBKEY_USAGE_SIG;
3020       else if (algo == PUBKEY_ALGO_RSA)
3021         keyuse = for_subkey? PUBKEY_USAGE_ENC : PUBKEY_USAGE_SIG;
3022       else
3023         keyuse = PUBKEY_USAGE_ENC;
3024     }
3025   else if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA
3026            || algo == PUBKEY_ALGO_DSA)
3027     {
3028       keyuse &= ~PUBKEY_USAGE_ENC; /* Forbid encryption.  */
3029     }
3030   else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ELGAMAL_E)
3031     {
3032       keyuse = PUBKEY_USAGE_ENC;   /* Allow only encryption.  */
3033     }
3034
3035   /* Make sure a primary key can certify.  */
3036   if (!for_subkey)
3037     keyuse |= PUBKEY_USAGE_CERT;
3038
3039   /* Check that usage is actually possible.  */
3040   if (/**/((keyuse & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
3041            && !pubkey_get_nsig (algo))
3042        || ((keyuse & PUBKEY_USAGE_ENC)
3043            && !pubkey_get_nenc (algo))
3044        || (for_subkey && (keyuse & PUBKEY_USAGE_CERT)))
3045     return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3046
3047   /* Return values.  */
3048   if (r_algo)
3049     *r_algo = algo;
3050   if (r_size)
3051     {
3052       unsigned int min, def, max;
3053
3054       /* Make sure the keysize is in the allowed range.  */
3055       def = get_keysize_range (algo, &min, &max);
3056       if (!size)
3057         size = def;
3058       else if (size < min)
3059         size = min;
3060       else if (size > max)
3061         size = max;
3062
3063       *r_size = fixup_keysize (size, algo, 1);
3064     }
3065   if (r_keyuse)
3066     *r_keyuse = keyuse;
3067   if (r_curve)
3068     *r_curve = curve;
3069
3070   return 0;
3071 }
3072
3073 /* Parse and return the standard key generation parameter.
3074  * The string is expected to be in this format:
3075  *
3076  *   ALGO[/FLAGS][+SUBALGO[/FLAGS]]
3077  *
3078  * Here ALGO is a string in the same format as printed by the
3079  * keylisting.  For example:
3080  *
3081  *   rsa3072 := RSA with 3072 bit.
3082  *   dsa2048 := DSA with 2048 bit.
3083  *   elg2048 := Elgamal with 2048 bit.
3084  *   ed25519 := EDDSA using curve Ed25519.
3085  *   cv25519 := ECDH using curve Curve25519.
3086  *   nistp256:= ECDSA or ECDH using curve NIST P-256
3087  *
3088  * All strings with an unknown prefix are considered an elliptic
3089  * curve.  Curves which have no implicit algorithm require that FLAGS
3090  * is given to select whether ECDSA or ECDH is used; this can eoither
3091  * be done using an algorithm keyword or usage keywords.
3092  *
3093  * FLAGS is a comma delimited string of keywords:
3094  *
3095  *   cert := Allow usage Certify
3096  *   sign := Allow usage Sign
3097  *   encr := Allow usage Encrypt
3098  *   auth := Allow usage Authentication
3099  *   encrypt := Alias for "encr"
3100  *   ecdsa := Use algorithm ECDSA.
3101  *   eddsa := Use algorithm EdDSA.
3102  *   ecdh  := Use algorithm ECDH.
3103  *
3104  * There are several defaults and fallbacks depending on the
3105  * algorithm.  PART can be used to select which part of STRING is
3106  * used:
3107  *   -1 := Both parts
3108  *    0 := Only the part of the primary key
3109  *    1 := If there is one part parse that one, if there are
3110  *         two parts parse the second part.  Always return
3111  *         in the args for the primary key (R_ALGO,....).
3112  *
3113  */
3114 gpg_error_t
3115 parse_key_parameter_string (const char *string, int part,
3116                             int *r_algo, unsigned int *r_size,
3117                             unsigned *r_keyuse,
3118                             char const **r_curve,
3119                             int *r_subalgo, unsigned int *r_subsize,
3120                             unsigned *r_subkeyuse,
3121                             char const **r_subcurve)
3122 {
3123   gpg_error_t err = 0;
3124   char *primary, *secondary;
3125
3126   if (r_algo)
3127     *r_algo = 0;
3128   if (r_size)
3129     *r_size = 0;
3130   if (r_keyuse)
3131     *r_keyuse = 0;
3132   if (r_curve)
3133     *r_curve = NULL;
3134   if (r_subalgo)
3135     *r_subalgo = 0;
3136   if (r_subsize)
3137     *r_subsize = 0;
3138   if (r_subkeyuse)
3139     *r_subkeyuse = 0;
3140   if (r_subcurve)
3141     *r_subcurve = NULL;
3142
3143   if (!string || !*string
3144       || !strcmp (string, "default") || !strcmp (string, "-"))
3145     string = get_default_pubkey_algo ();
3146   else if (!strcmp (string, "future-default"))
3147     string = FUTURE_STD_KEY_PARAM;
3148
3149   primary = xstrdup (string);
3150   secondary = strchr (primary, '+');
3151   if (secondary)
3152     *secondary++ = 0;
3153   if (part == -1 || part == 0)
3154     {
3155       err = parse_key_parameter_part (primary, 0, r_algo, r_size,
3156                                       r_keyuse, r_curve);
3157       if (!err && part == -1)
3158         err = parse_key_parameter_part (secondary, 1, r_subalgo, r_subsize,
3159                                         r_subkeyuse, r_subcurve);
3160     }
3161   else if (part == 1)
3162     {
3163       /* If we have SECONDARY, use that part.  If there is only one
3164        * part consider this to be the subkey algo.  */
3165       err = parse_key_parameter_part (secondary? secondary : primary, 1,
3166                                       r_algo, r_size, r_keyuse, r_curve);
3167     }
3168
3169   xfree (primary);
3170
3171   return err;
3172 }
3173
3174
3175
3176 /* Append R to the linked list PARA.  */
3177 static void
3178 append_to_parameter (struct para_data_s *para, struct para_data_s *r)
3179 {
3180   log_assert (para);
3181   while (para->next)
3182     para = para->next;
3183   para->next = r;
3184 }
3185
3186 /* Release the parameter list R.  */
3187 static void
3188 release_parameter_list (struct para_data_s *r)
3189 {
3190   struct para_data_s *r2;
3191
3192   for (; r ; r = r2)
3193     {
3194       r2 = r->next;
3195       if (r->key == pPASSPHRASE && *r->u.value)
3196         wipememory (r->u.value, strlen (r->u.value));
3197       xfree (r);
3198     }
3199 }
3200
3201 static struct para_data_s *
3202 get_parameter( struct para_data_s *para, enum para_name key )
3203 {
3204     struct para_data_s *r;
3205
3206     for( r = para; r && r->key != key; r = r->next )
3207         ;
3208     return r;
3209 }
3210
3211 static const char *
3212 get_parameter_value( struct para_data_s *para, enum para_name key )
3213 {
3214     struct para_data_s *r = get_parameter( para, key );
3215     return (r && *r->u.value)? r->u.value : NULL;
3216 }
3217
3218
3219 /* This is similar to get_parameter_value but also returns the empty
3220    string.  This is required so that quick_generate_keypair can use an
3221    empty Passphrase to specify no-protection.  */
3222 static const char *
3223 get_parameter_passphrase (struct para_data_s *para)
3224 {
3225   struct para_data_s *r = get_parameter (para, pPASSPHRASE);
3226   return r ? r->u.value : NULL;
3227 }
3228
3229
3230 static int
3231 get_parameter_algo( struct para_data_s *para, enum para_name key,
3232                     int *r_default)
3233 {
3234   int i;
3235   struct para_data_s *r = get_parameter( para, key );
3236
3237   if (r_default)
3238     *r_default = 0;
3239
3240   if (!r)
3241     return -1;
3242
3243   /* Note that we need to handle the ECC algorithms specified as
3244      strings directly because Libgcrypt folds them all to ECC.  */
3245   if (!ascii_strcasecmp (r->u.value, "default"))
3246     {
3247       /* Note: If you change this default algo, remember to change it
3248        * also in gpg.c:gpgconf_list.  */
3249       /* FIXME: We only allow the algo here and have a separate thing
3250        * for the curve etc.  That is a ugly but demanded for backward
3251        * compatibility with the batch key generation.  It would be
3252        * better to make full use of parse_key_parameter_string.  */
3253       parse_key_parameter_string (NULL, 0,
3254                                   &i, NULL, NULL, NULL,
3255                                   NULL, NULL, NULL, NULL);
3256
3257       if (r_default)
3258         *r_default = 1;
3259     }
3260   else if (digitp (r->u.value))
3261     i = atoi( r->u.value );
3262   else if (!strcmp (r->u.value, "ELG-E")
3263            || !strcmp (r->u.value, "ELG"))
3264     i = PUBKEY_ALGO_ELGAMAL_E;
3265   else if (!ascii_strcasecmp (r->u.value, "EdDSA"))
3266     i = PUBKEY_ALGO_EDDSA;
3267   else if (!ascii_strcasecmp (r->u.value, "ECDSA"))
3268     i = PUBKEY_ALGO_ECDSA;
3269   else if (!ascii_strcasecmp (r->u.value, "ECDH"))
3270     i = PUBKEY_ALGO_ECDH;
3271   else
3272     i = map_pk_gcry_to_openpgp (gcry_pk_map_name (r->u.value));
3273
3274   if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
3275     i = 0; /* we don't want to allow generation of these algorithms */
3276   return i;
3277 }
3278
3279
3280 /* Parse a usage string.  The usage keywords "auth", "sign", "encr"
3281  * may be delimited by space, tab, or comma.  On error -1 is returned
3282  * instead of the usage flags.  */
3283 static int
3284 parse_usagestr (const char *usagestr)
3285 {
3286   gpg_error_t err;
3287   char **tokens = NULL;
3288   const char *s;
3289   int i;
3290   unsigned int use = 0;
3291
3292   tokens = strtokenize (usagestr, " \t,");
3293   if (!tokens)
3294     {
3295       err = gpg_error_from_syserror ();
3296       log_error ("strtokenize failed: %s\n", gpg_strerror (err));
3297       return -1;
3298     }
3299
3300   for (i=0; (s = tokens[i]); i++)
3301     {
3302       if (!*s)
3303         ;
3304       else if (!ascii_strcasecmp (s, "sign"))
3305         use |= PUBKEY_USAGE_SIG;
3306       else if (!ascii_strcasecmp (s, "encrypt")
3307                 || !ascii_strcasecmp (s, "encr"))
3308         use |= PUBKEY_USAGE_ENC;
3309       else if (!ascii_strcasecmp (s, "auth"))
3310         use |= PUBKEY_USAGE_AUTH;
3311       else if (!ascii_strcasecmp (s, "cert"))
3312         use |= PUBKEY_USAGE_CERT;
3313       else
3314         {
3315           xfree (tokens);
3316           return -1; /* error */
3317         }
3318     }
3319
3320   xfree (tokens);
3321   return use;
3322 }
3323
3324
3325 /*
3326  * Parse the usage parameter and set the keyflags.  Returns -1 on
3327  * error, 0 for no usage given or 1 for usage available.
3328  */
3329 static int
3330 parse_parameter_usage (const char *fname,
3331                        struct para_data_s *para, enum para_name key)
3332 {
3333   struct para_data_s *r = get_parameter( para, key );
3334   int i;
3335
3336   if (!r)
3337     return 0; /* none (this is an optional parameter)*/
3338
3339   i = parse_usagestr (r->u.value);
3340   if (i == -1)
3341     {
3342       log_error ("%s:%d: invalid usage list\n", fname, r->lnr );
3343       return -1; /* error */
3344     }
3345
3346   r->u.usage = i;
3347   return 1;
3348 }
3349
3350
3351 static int
3352 parse_revocation_key (const char *fname,
3353                       struct para_data_s *para, enum para_name key)
3354 {
3355   struct para_data_s *r = get_parameter( para, key );
3356   struct revocation_key revkey;
3357   char *pn;
3358   int i;
3359
3360   if( !r )
3361     return 0; /* none (this is an optional parameter) */
3362
3363   pn = r->u.value;
3364
3365   revkey.class=0x80;
3366   revkey.algid=atoi(pn);
3367   if(!revkey.algid)
3368     goto fail;
3369
3370   /* Skip to the fpr */
3371   while(*pn && *pn!=':')
3372     pn++;
3373
3374   if(*pn!=':')
3375     goto fail;
3376
3377   pn++;
3378
3379   for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
3380     {
3381       int c=hextobyte(pn);
3382       if(c==-1)
3383         goto fail;
3384
3385       revkey.fpr[i]=c;
3386     }
3387
3388   /* skip to the tag */
3389   while(*pn && *pn!='s' && *pn!='S')
3390     pn++;
3391
3392   if(ascii_strcasecmp(pn,"sensitive")==0)
3393     revkey.class|=0x40;
3394
3395   memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
3396
3397   return 0;
3398
3399   fail:
3400   log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
3401   return -1; /* error */
3402 }
3403
3404
3405 static u32
3406 get_parameter_u32( struct para_data_s *para, enum para_name key )
3407 {
3408   struct para_data_s *r = get_parameter( para, key );
3409
3410   if( !r )
3411     return 0;
3412   if( r->key == pKEYCREATIONDATE )
3413     return r->u.creation;
3414   if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
3415     return r->u.expire;
3416   if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
3417     return r->u.usage;
3418
3419   return (unsigned int)strtoul( r->u.value, NULL, 10 );
3420 }
3421
3422 static unsigned int
3423 get_parameter_uint( struct para_data_s *para, enum para_name key )
3424 {
3425     return get_parameter_u32( para, key );
3426 }
3427
3428 static struct revocation_key *
3429 get_parameter_revkey( struct para_data_s *para, enum para_name key )
3430 {
3431     struct para_data_s *r = get_parameter( para, key );
3432     return r? &r->u.revkey : NULL;
3433 }
3434
3435 static int
3436 proc_parameter_file (ctrl_t ctrl, struct para_data_s *para, const char *fname,
3437                      struct output_control_s *outctrl, int card )
3438 {
3439   struct para_data_s *r;
3440   const char *s1, *s2, *s3;
3441   size_t n;
3442   char *p;
3443   int is_default = 0;
3444   int have_user_id = 0;
3445   int err, algo;
3446
3447   /* Check that we have all required parameters. */
3448   r = get_parameter( para, pKEYTYPE );
3449   if(r)
3450     {
3451       algo = get_parameter_algo (para, pKEYTYPE, &is_default);
3452       if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
3453         {
3454           log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3455           return -1;
3456         }
3457     }
3458   else
3459     {
3460       log_error ("%s: no Key-Type specified\n",fname);
3461       return -1;
3462     }
3463
3464   err = parse_parameter_usage (fname, para, pKEYUSAGE);
3465   if (!err)
3466     {
3467       /* Default to algo capabilities if key-usage is not provided and
3468          no default algorithm has been requested.  */
3469       r = xmalloc_clear(sizeof(*r));
3470       r->key = pKEYUSAGE;
3471       r->u.usage = (is_default
3472                     ? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
3473                     : openpgp_pk_algo_usage(algo));
3474       append_to_parameter (para, r);
3475     }
3476   else if (err == -1)
3477     return -1;
3478   else
3479     {
3480       r = get_parameter (para, pKEYUSAGE);
3481       if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3482         {
3483           log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
3484                      fname, r->lnr, algo);
3485           return -1;
3486         }
3487     }
3488
3489   is_default = 0;
3490   r = get_parameter( para, pSUBKEYTYPE );
3491   if(r)
3492     {
3493       algo = get_parameter_algo (para, pSUBKEYTYPE, &is_default);
3494       if (openpgp_pk_test_algo (algo))
3495         {
3496           log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3497           return -1;
3498         }
3499
3500       err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
3501       if (!err)
3502         {
3503           /* Default to algo capabilities if subkey-usage is not
3504              provided */
3505           r = xmalloc_clear (sizeof(*r));
3506           r->key = pSUBKEYUSAGE;
3507           r->u.usage = (is_default
3508                         ? PUBKEY_USAGE_ENC
3509                         : openpgp_pk_algo_usage (algo));
3510           append_to_parameter (para, r);
3511         }
3512       else if (err == -1)
3513         return -1;
3514       else
3515         {
3516           r = get_parameter (para, pSUBKEYUSAGE);
3517           if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3518             {
3519               log_error ("%s:%d: specified Subkey-Usage not allowed"
3520                          " for algo %d\n", fname, r->lnr, algo);
3521               return -1;
3522             }
3523         }
3524     }
3525
3526
3527   if( get_parameter_value( para, pUSERID ) )
3528     have_user_id=1;
3529   else
3530     {
3531       /* create the formatted user ID */
3532       s1 = get_parameter_value( para, pNAMEREAL );
3533       s2 = get_parameter_value( para, pNAMECOMMENT );
3534       s3 = get_parameter_value( para, pNAMEEMAIL );
3535       if( s1 || s2 || s3 )
3536         {
3537           n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
3538           r = xmalloc_clear( sizeof *r + n + 20 );
3539           r->key = pUSERID;
3540           p = r->u.value;
3541           if( s1 )
3542             p = stpcpy(p, s1 );
3543           if( s2 )
3544             p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
3545           if( s3 )
3546             p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
3547           append_to_parameter (para, r);
3548           have_user_id=1;
3549         }
3550     }
3551
3552   if(!have_user_id)
3553     {
3554       log_error("%s: no User-ID specified\n",fname);
3555       return -1;
3556     }
3557
3558   /* Set preferences, if any. */
3559   keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
3560
3561   /* Set keyserver, if any. */
3562   s1=get_parameter_value( para, pKEYSERVER );
3563   if(s1)
3564     {
3565       struct keyserver_spec *spec;
3566
3567       spec = parse_keyserver_uri (s1, 1);
3568       if(spec)
3569         {
3570           free_keyserver_spec(spec);
3571           opt.def_keyserver_url=s1;
3572         }
3573       else
3574         {
3575           r = get_parameter (para, pKEYSERVER);
3576           log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
3577           return -1;
3578         }
3579     }
3580
3581   /* Set revoker, if any. */
3582   if (parse_revocation_key (fname, para, pREVOKER))
3583     return -1;
3584
3585
3586   /* Make KEYCREATIONDATE from Creation-Date.  */
3587   r = get_parameter (para, pCREATIONDATE);
3588   if (r && *r->u.value)
3589     {
3590       u32 seconds;
3591
3592       seconds = parse_creation_string (r->u.value);
3593       if (!seconds)
3594         {
3595           log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
3596           return -1;
3597         }
3598       r->u.creation = seconds;
3599       r->key = pKEYCREATIONDATE;  /* Change that entry. */
3600     }
3601
3602   /* Make KEYEXPIRE from Expire-Date.  */
3603   r = get_parameter( para, pEXPIREDATE );
3604   if( r && *r->u.value )
3605     {
3606       u32 seconds;
3607
3608       seconds = parse_expire_string( r->u.value );
3609       if( seconds == (u32)-1 )
3610         {
3611           log_error("%s:%d: invalid expire date\n", fname, r->lnr );
3612           return -1;
3613         }
3614       r->u.expire = seconds;
3615       r->key = pKEYEXPIRE;  /* change hat entry */
3616       /* also set it for the subkey */
3617       r = xmalloc_clear( sizeof *r + 20 );
3618       r->key = pSUBKEYEXPIRE;
3619       r->u.expire = seconds;
3620       append_to_parameter (para, r);
3621     }
3622
3623   do_generate_keypair (ctrl, para, outctrl, card );
3624   return 0;
3625 }
3626
3627
3628 /****************
3629  * Kludge to allow non interactive key generation controlled
3630  * by a parameter file.
3631  * Note, that string parameters are expected to be in UTF-8
3632  */
3633 static void
3634 read_parameter_file (ctrl_t ctrl, const char *fname )
3635 {
3636     static struct { const char *name;
3637                     enum para_name key;
3638     } keywords[] = {
3639         { "Key-Type",       pKEYTYPE},
3640         { "Key-Length",     pKEYLENGTH },
3641         { "Key-Curve",      pKEYCURVE },
3642         { "Key-Usage",      pKEYUSAGE },
3643         { "Subkey-Type",    pSUBKEYTYPE },
3644         { "Subkey-Length",  pSUBKEYLENGTH },
3645         { "Subkey-Curve",   pSUBKEYCURVE },
3646         { "Subkey-Usage",   pSUBKEYUSAGE },
3647         { "Name-Real",      pNAMEREAL },
3648         { "Name-Email",     pNAMEEMAIL },
3649         { "Name-Comment",   pNAMECOMMENT },
3650         { "Expire-Date",    pEXPIREDATE },
3651         { "Creation-Date",  pCREATIONDATE },
3652         { "Passphrase",     pPASSPHRASE },
3653         { "Preferences",    pPREFERENCES },
3654         { "Revoker",        pREVOKER },
3655         { "Handle",         pHANDLE },
3656         { "Keyserver",      pKEYSERVER },
3657         { NULL, 0 }
3658     };
3659     IOBUF fp;
3660     byte *line;
3661     unsigned int maxlen, nline;
3662     char *p;
3663     int lnr;
3664     const char *err = NULL;
3665     struct para_data_s *para, *r;
3666     int i;
3667     struct output_control_s outctrl;
3668
3669     memset( &outctrl, 0, sizeof( outctrl ) );
3670     outctrl.pub.afx = new_armor_context ();
3671
3672     if( !fname || !*fname)
3673       fname = "-";
3674
3675     fp = iobuf_open (fname);
3676     if (fp && is_secured_file (iobuf_get_fd (fp)))
3677       {
3678         iobuf_close (fp);
3679         fp = NULL;
3680         gpg_err_set_errno (EPERM);
3681       }
3682     if (!fp) {
3683       log_error (_("can't open '%s': %s\n"), fname, strerror(errno) );
3684       return;
3685     }
3686     iobuf_ioctl (fp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
3687
3688     lnr = 0;
3689     err = NULL;
3690     para = NULL;
3691     maxlen = 1024;
3692     line = NULL;
3693     while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
3694         char *keyword, *value;
3695
3696         lnr++;
3697         if( !maxlen ) {
3698             err = "line too long";
3699             break;
3700         }
3701         for( p = line; isspace(*(byte*)p); p++ )
3702             ;
3703         if( !*p || *p == '#' )
3704             continue;
3705         keyword = p;
3706         if( *keyword == '%' ) {
3707             for( ; !isspace(*(byte*)p); p++ )
3708                 ;
3709             if( *p )
3710                 *p++ = 0;
3711             for( ; isspace(*(byte*)p); p++ )
3712                 ;
3713             value = p;
3714             trim_trailing_ws( value, strlen(value) );
3715             if( !ascii_strcasecmp( keyword, "%echo" ) )
3716                 log_info("%s\n", value );
3717             else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
3718                 outctrl.dryrun = 1;
3719             else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
3720               ; /* Dummy for backward compatibility. */
3721             else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
3722               ; /* Dummy for backward compatibility. */
3723             else if( !ascii_strcasecmp( keyword, "%no-protection" ) )
3724                 outctrl.keygen_flags |= KEYGEN_FLAG_NO_PROTECTION;
3725             else if( !ascii_strcasecmp( keyword, "%transient-key" ) )
3726                 outctrl.keygen_flags |= KEYGEN_FLAG_TRANSIENT_KEY;
3727             else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
3728                 outctrl.lnr = lnr;
3729                 if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3730                   print_status_key_not_created
3731                     (get_parameter_value (para, pHANDLE));
3732                 release_parameter_list( para );
3733                 para = NULL;
3734             }
3735             else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
3736                 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
3737                     ; /* still the same file - ignore it */
3738                 else {
3739                     xfree( outctrl.pub.newfname );
3740                     outctrl.pub.newfname = xstrdup( value );
3741                     outctrl.use_files = 1;
3742                 }
3743             }
3744             else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
3745               /* Ignore this command.  */
3746             }
3747             else
3748                 log_info("skipping control '%s' (%s)\n", keyword, value );
3749
3750
3751             continue;
3752         }
3753
3754
3755         if( !(p = strchr( p, ':' )) || p == keyword ) {
3756             err = "missing colon";
3757             break;
3758         }
3759         if( *p )
3760             *p++ = 0;
3761         for( ; isspace(*(byte*)p); p++ )
3762             ;
3763         if( !*p ) {
3764             err = "missing argument";
3765             break;
3766         }
3767         value = p;
3768         trim_trailing_ws( value, strlen(value) );
3769
3770         for(i=0; keywords[i].name; i++ ) {
3771             if( !ascii_strcasecmp( keywords[i].name, keyword ) )
3772                 break;
3773         }
3774         if( !keywords[i].name ) {
3775             err = "unknown keyword";
3776             break;
3777         }
3778         if( keywords[i].key != pKEYTYPE && !para ) {
3779             err = "parameter block does not start with \"Key-Type\"";
3780             break;
3781         }
3782
3783         if( keywords[i].key == pKEYTYPE && para ) {
3784             outctrl.lnr = lnr;
3785             if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3786               print_status_key_not_created
3787                 (get_parameter_value (para, pHANDLE));
3788             release_parameter_list( para );
3789             para = NULL;
3790         }
3791         else {
3792             for( r = para; r; r = r->next ) {
3793                 if( r->key == keywords[i].key )
3794                     break;
3795             }
3796             if( r ) {
3797                 err = "duplicate keyword";
3798                 break;
3799             }
3800         }
3801         r = xmalloc_clear( sizeof *r + strlen( value ) );
3802         r->lnr = lnr;
3803         r->key = keywords[i].key;
3804         strcpy( r->u.value, value );
3805         r->next = para;
3806         para = r;
3807     }
3808     if( err )
3809         log_error("%s:%d: %s\n", fname, lnr, err );
3810     else if( iobuf_error (fp) ) {
3811         log_error("%s:%d: read error\n", fname, lnr);
3812     }
3813     else if( para ) {
3814         outctrl.lnr = lnr;
3815         if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3816           print_status_key_not_created (get_parameter_value (para, pHANDLE));
3817     }
3818
3819     if( outctrl.use_files ) { /* close open streams */
3820         iobuf_close( outctrl.pub.stream );
3821
3822         /* Must invalidate that ugly cache to actually close it.  */
3823         if (outctrl.pub.fname)
3824           iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
3825                        0, (char*)outctrl.pub.fname);
3826
3827         xfree( outctrl.pub.fname );
3828         xfree( outctrl.pub.newfname );
3829     }
3830
3831     xfree (line);
3832     release_parameter_list( para );
3833     iobuf_close (fp);
3834     release_armor_context (outctrl.pub.afx);
3835 }
3836
3837
3838 /* Helper for quick_generate_keypair.  */
3839 static struct para_data_s *
3840 quickgen_set_para (struct para_data_s *para, int for_subkey,
3841                    int algo, int nbits, const char *curve, unsigned int use)
3842 {
3843   struct para_data_s *r;
3844
3845   r = xmalloc_clear (sizeof *r + 30);
3846   r->key = for_subkey? pSUBKEYUSAGE :  pKEYUSAGE;
3847   if (use)
3848     snprintf (r->u.value, 30, "%s%s%s%s",
3849               (use & PUBKEY_USAGE_ENC)?  "encr " : "",
3850               (use & PUBKEY_USAGE_SIG)?  "sign " : "",
3851               (use & PUBKEY_USAGE_AUTH)? "auth " : "",
3852               (use & PUBKEY_USAGE_CERT)? "cert " : "");
3853   else
3854     strcpy (r->u.value, for_subkey ? "encr" : "sign");
3855   r->next = para;
3856   para = r;
3857   r = xmalloc_clear (sizeof *r + 20);
3858   r->key = for_subkey? pSUBKEYTYPE : pKEYTYPE;
3859   snprintf (r->u.value, 20, "%d", algo);
3860   r->next = para;
3861   para = r;
3862
3863   if (curve)
3864     {
3865       r = xmalloc_clear (sizeof *r + strlen (curve));
3866       r->key = for_subkey? pSUBKEYCURVE : pKEYCURVE;
3867       strcpy (r->u.value, curve);
3868       r->next = para;
3869       para = r;
3870     }
3871   else
3872     {
3873       r = xmalloc_clear (sizeof *r + 20);
3874       r->key = for_subkey? pSUBKEYLENGTH : pKEYLENGTH;
3875       sprintf (r->u.value, "%u", nbits);
3876       r->next = para;
3877       para = r;
3878     }
3879
3880   return para;
3881 }
3882
3883
3884 /*
3885  * Unattended generation of a standard key.
3886  */
3887 void
3888 quick_generate_keypair (ctrl_t ctrl, const char *uid, const char *algostr,
3889                         const char *usagestr, const char *expirestr)
3890 {
3891   gpg_error_t err;
3892   struct para_data_s *para = NULL;
3893   struct para_data_s *r;
3894   struct output_control_s outctrl;
3895   int use_tty;
3896
3897   memset (&outctrl, 0, sizeof outctrl);
3898
3899   use_tty = (!opt.batch && !opt.answer_yes
3900              && !*algostr && !*usagestr && !*expirestr
3901              && !cpr_enabled ()
3902              && gnupg_isatty (fileno (stdin))
3903              && gnupg_isatty (fileno (stdout))
3904              && gnupg_isatty (fileno (stderr)));
3905
3906   r = xmalloc_clear (sizeof *r + strlen (uid));
3907   r->key = pUSERID;
3908   strcpy (r->u.value, uid);
3909   r->next = para;
3910   para = r;
3911
3912   uid = trim_spaces (r->u.value);
3913   if (!*uid || (!opt.allow_freeform_uid && !is_valid_user_id (uid)))
3914     {
3915       log_error (_("Key generation failed: %s\n"),
3916                  gpg_strerror (GPG_ERR_INV_USER_ID));
3917       goto leave;
3918     }
3919
3920   /* If gpg is directly used on the console ask whether a key with the
3921      given user id shall really be created.  */
3922   if (use_tty)
3923     {
3924       tty_printf (_("About to create a key for:\n    \"%s\"\n\n"), uid);
3925       if (!cpr_get_answer_is_yes_def ("quick_keygen.okay",
3926                                       _("Continue? (Y/n) "), 1))
3927         goto leave;
3928     }
3929
3930   /* Check whether such a user ID already exists.  */
3931   {
3932     KEYDB_HANDLE kdbhd;
3933     KEYDB_SEARCH_DESC desc;
3934
3935     memset (&desc, 0, sizeof desc);
3936     desc.mode = KEYDB_SEARCH_MODE_EXACT;
3937     desc.u.name = uid;
3938
3939     kdbhd = keydb_new ();
3940     if (!kdbhd)
3941       goto leave;
3942
3943     err = keydb_search (kdbhd, &desc, 1, NULL);
3944     keydb_release (kdbhd);
3945     if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
3946       {
3947         log_info (_("A key for \"%s\" already exists\n"), uid);
3948         if (opt.answer_yes)
3949           ;
3950         else if (!use_tty
3951                  || !cpr_get_answer_is_yes_def ("quick_keygen.force",
3952                                                 _("Create anyway? (y/N) "), 0))
3953           {
3954             write_status_error ("genkey", gpg_error (304));
3955             log_inc_errorcount ();  /* we used log_info */
3956             goto leave;
3957           }
3958         log_info (_("creating anyway\n"));
3959       }
3960   }
3961
3962   if (!*expirestr || strcmp (expirestr, "-") == 0)
3963     expirestr = default_expiration_interval;
3964
3965   if ((!*algostr || !strcmp (algostr, "default")
3966        || !strcmp (algostr, "future-default"))
3967       && (!*usagestr || !strcmp (usagestr, "default")
3968           || !strcmp (usagestr, "-")))
3969     {
3970       /* Use default key parameters.  */
3971       int algo, subalgo;
3972       unsigned int size, subsize;
3973       unsigned int keyuse, subkeyuse;
3974       const char *curve, *subcurve;
3975
3976       err = parse_key_parameter_string (algostr, -1,
3977                                         &algo, &size, &keyuse, &curve,
3978                                         &subalgo, &subsize, &subkeyuse,
3979                                         &subcurve);
3980       if (err)
3981         {
3982           log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
3983           goto leave;
3984         }
3985
3986       para = quickgen_set_para (para, 0, algo, size, curve, keyuse);
3987       if (subalgo)
3988         para = quickgen_set_para (para, 1,
3989                                   subalgo, subsize, subcurve, subkeyuse);
3990
3991       if (*expirestr)
3992         {
3993           u32 expire;
3994
3995           expire = parse_expire_string (expirestr);
3996           if (expire == (u32)-1 )
3997             {
3998               err = gpg_error (GPG_ERR_INV_VALUE);
3999               log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
4000               goto leave;
4001             }
4002           r = xmalloc_clear (sizeof *r + 20);
4003           r->key = pKEYEXPIRE;
4004           r->u.expire = expire;
4005           r->next = para;
4006           para = r;
4007         }
4008     }
4009   else
4010     {
4011       /* Extended unattended mode.  Creates only the primary key. */
4012       int algo;
4013       unsigned int use;
4014       u32 expire;
4015       unsigned int nbits;
4016       char *curve;
4017
4018       err = parse_algo_usage_expire (ctrl, 0, algostr, usagestr, expirestr,
4019                                      &algo, &use, &expire, &nbits, &curve);
4020       if (err)
4021         {
4022           log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
4023           goto leave;
4024         }
4025
4026       para = quickgen_set_para (para, 0, algo, nbits, curve, use);
4027       r = xmalloc_clear (sizeof *r + 20);
4028       r->key = pKEYEXPIRE;
4029       r->u.expire = expire;
4030       r->next = para;
4031       para = r;
4032     }
4033
4034   /* If the pinentry loopback mode is not and we have a static
4035      passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
4036      mode), we use that passphrase for the new key.  */
4037   if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
4038       && have_static_passphrase ())
4039     {
4040       const char *s = get_static_passphrase ();
4041
4042       r = xmalloc_clear (sizeof *r + strlen (s));
4043       r->key = pPASSPHRASE;
4044       strcpy (r->u.value, s);
4045       r->next = para;
4046       para = r;
4047     }
4048
4049   proc_parameter_file (ctrl, para, "[internal]", &outctrl, 0);
4050
4051  leave:
4052   release_parameter_list (para);
4053 }
4054
4055
4056 /*
4057  * Generate a keypair (fname is only used in batch mode) If
4058  * CARD_SERIALNO is not NULL the function will create the keys on an
4059  * OpenPGP Card.  If CARD_BACKUP_KEY has been set and CARD_SERIALNO is
4060  * NOT NULL, the encryption key for the card is generated on the host,
4061  * imported to the card and a backup file created by gpg-agent.  If
4062  * FULL is not set only the basic prompts are used (except for batch
4063  * mode).
4064  */
4065 void
4066 generate_keypair (ctrl_t ctrl, int full, const char *fname,
4067                   const char *card_serialno, int card_backup_key)
4068 {
4069   gpg_error_t err;
4070   unsigned int nbits;
4071   char *uid = NULL;
4072   int algo;
4073   unsigned int use;
4074   int both = 0;
4075   u32 expire;
4076   struct para_data_s *para = NULL;
4077   struct para_data_s *r;
4078   struct output_control_s outctrl;
4079
4080 #ifndef ENABLE_CARD_SUPPORT
4081   (void)card_backup_key;
4082 #endif
4083
4084   memset( &outctrl, 0, sizeof( outctrl ) );
4085
4086   if (opt.batch && card_serialno)
4087     {
4088       /* We don't yet support unattended key generation. */
4089       log_error (_("can't do this in batch mode\n"));
4090       return;
4091     }
4092
4093   if (opt.batch)
4094     {
4095       read_parameter_file (ctrl, fname);
4096       return;
4097     }
4098
4099   if (card_serialno)
4100     {
4101 #ifdef ENABLE_CARD_SUPPORT
4102       struct agent_card_info_s info;
4103
4104       memset (&info, 0, sizeof (info));
4105       err = agent_scd_getattr ("KEY-ATTR", &info);
4106       if (err)
4107         {
4108           log_error (_("error getting current key info: %s\n"),
4109                      gpg_strerror (err));
4110           return;
4111         }
4112
4113       r = xcalloc (1, sizeof *r + strlen (card_serialno) );
4114       r->key = pSERIALNO;
4115       strcpy( r->u.value, card_serialno);
4116       r->next = para;
4117       para = r;
4118
4119       r = xcalloc (1, sizeof *r + 20 );
4120       r->key = pKEYTYPE;
4121       sprintf( r->u.value, "%d", info.key_attr[0].algo );
4122       r->next = para;
4123       para = r;
4124       r = xcalloc (1, sizeof *r + 20 );
4125       r->key = pKEYUSAGE;
4126       strcpy (r->u.value, "sign");
4127       r->next = para;
4128       para = r;
4129
4130       r = xcalloc (1, sizeof *r + 20 );
4131       r->key = pSUBKEYTYPE;
4132       sprintf( r->u.value, "%d", info.key_attr[1].algo );
4133       r->next = para;
4134       para = r;
4135       r = xcalloc (1, sizeof *r + 20 );
4136       r->key = pSUBKEYUSAGE;
4137       strcpy (r->u.value, "encrypt");
4138       r->next = para;
4139       para = r;
4140       if (info.key_attr[1].algo == PUBKEY_ALGO_RSA)
4141         {
4142           r = xcalloc (1, sizeof *r + 20 );
4143           r->key = pSUBKEYLENGTH;
4144           sprintf( r->u.value, "%u", info.key_attr[1].nbits);
4145           r->next = para;
4146           para = r;
4147         }
4148       else if (info.key_attr[1].algo == PUBKEY_ALGO_ECDSA
4149                || info.key_attr[1].algo == PUBKEY_ALGO_EDDSA
4150                || info.key_attr[1].algo == PUBKEY_ALGO_ECDH)
4151         {
4152           r = xcalloc (1, sizeof *r + strlen (info.key_attr[1].curve));
4153           r->key = pSUBKEYCURVE;
4154           strcpy (r->u.value, info.key_attr[1].curve);
4155           r->next = para;
4156           para = r;
4157         }
4158
4159       r = xcalloc (1, sizeof *r + 20 );
4160       r->key = pAUTHKEYTYPE;
4161       sprintf( r->u.value, "%d", info.key_attr[2].algo );
4162       r->next = para;
4163       para = r;
4164
4165       if (card_backup_key)
4166         {
4167           r = xcalloc (1, sizeof *r + 1);
4168           r->key = pCARDBACKUPKEY;
4169           strcpy (r->u.value, "1");
4170           r->next = para;
4171           para = r;
4172         }
4173 #endif /*ENABLE_CARD_SUPPORT*/
4174     }
4175   else if (full)  /* Full featured key generation.  */
4176     {
4177       int subkey_algo;
4178       char *curve = NULL;
4179
4180       /* Fixme: To support creating a primary key by keygrip we better
4181          also define the keyword for the parameter file.  Note that
4182          the subkey case will never be asserted if a keygrip has been
4183          given.  */
4184       algo = ask_algo (ctrl, 0, &subkey_algo, &use, NULL);
4185       if (subkey_algo)
4186         {
4187           /* Create primary and subkey at once.  */
4188           both = 1;
4189           if (algo == PUBKEY_ALGO_ECDSA
4190               || algo == PUBKEY_ALGO_EDDSA
4191               || algo == PUBKEY_ALGO_ECDH)
4192             {
4193               curve = ask_curve (&algo, &subkey_algo);
4194               r = xmalloc_clear( sizeof *r + 20 );
4195               r->key = pKEYTYPE;
4196               sprintf( r->u.value, "%d", algo);
4197               r->next = para;
4198               para = r;
4199               nbits = 0;
4200               r = xmalloc_clear (sizeof *r + strlen (curve));
4201               r->key = pKEYCURVE;
4202               strcpy (r->u.value, curve);
4203               r->next = para;
4204               para = r;
4205             }
4206           else
4207             {
4208               r = xmalloc_clear( sizeof *r + 20 );
4209               r->key = pKEYTYPE;
4210               sprintf( r->u.value, "%d", algo);
4211               r->next = para;
4212               para = r;
4213               nbits = ask_keysize (algo, 0);
4214               r = xmalloc_clear( sizeof *r + 20 );
4215               r->key = pKEYLENGTH;
4216               sprintf( r->u.value, "%u", nbits);
4217               r->next = para;
4218               para = r;
4219             }
4220           r = xmalloc_clear( sizeof *r + 20 );
4221           r->key = pKEYUSAGE;
4222           strcpy( r->u.value, "sign" );
4223           r->next = para;
4224           para = r;
4225
4226           r = xmalloc_clear( sizeof *r + 20 );
4227           r->key = pSUBKEYTYPE;
4228           sprintf( r->u.value, "%d", subkey_algo);
4229           r->next = para;
4230           para = r;
4231           r = xmalloc_clear( sizeof *r + 20 );
4232           r->key = pSUBKEYUSAGE;
4233           strcpy( r->u.value, "encrypt" );
4234           r->next = para;
4235           para = r;
4236
4237           if (algo == PUBKEY_ALGO_ECDSA
4238               || algo == PUBKEY_ALGO_EDDSA
4239               || algo == PUBKEY_ALGO_ECDH)
4240             {
4241               if (algo == PUBKEY_ALGO_EDDSA
4242                   && subkey_algo == PUBKEY_ALGO_ECDH)
4243                 {
4244                   /* Need to switch to a different curve for the
4245                      encryption key.  */
4246                   xfree (curve);
4247                   curve = xstrdup ("Curve25519");
4248                 }
4249               r = xmalloc_clear (sizeof *r + strlen (curve));
4250               r->key = pSUBKEYCURVE;
4251               strcpy (r->u.value, curve);
4252               r->next = para;
4253               para = r;
4254             }
4255         }
4256       else /* Create only a single key.  */
4257         {
4258           /* For ECC we need to ask for the curve before storing the
4259              algo because ask_curve may change the algo.  */
4260           if (algo == PUBKEY_ALGO_ECDSA
4261               || algo == PUBKEY_ALGO_EDDSA
4262               || algo == PUBKEY_ALGO_ECDH)
4263             {
4264               curve = ask_curve (&algo, NULL);
4265               r = xmalloc_clear (sizeof *r + strlen (curve));
4266               r->key = pKEYCURVE;
4267               strcpy (r->u.value, curve);
4268               r->next = para;
4269               para = r;
4270             }
4271
4272           r = xmalloc_clear( sizeof *r + 20 );
4273           r->key = pKEYTYPE;
4274           sprintf( r->u.value, "%d", algo );
4275           r->next = para;
4276           para = r;
4277
4278           if (use)
4279             {
4280               r = xmalloc_clear( sizeof *r + 25 );
4281               r->key = pKEYUSAGE;
4282               sprintf( r->u.value, "%s%s%s",
4283                        (use & PUBKEY_USAGE_SIG)? "sign ":"",
4284                        (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
4285                        (use & PUBKEY_USAGE_AUTH)? "auth":"" );
4286               r->next = para;
4287               para = r;
4288             }
4289           nbits = 0;
4290         }
4291
4292       if (algo == PUBKEY_ALGO_ECDSA
4293           || algo == PUBKEY_ALGO_EDDSA
4294           || algo == PUBKEY_ALGO_ECDH)
4295         {
4296           /* The curve has already been set.  */
4297         }
4298       else
4299         {
4300           nbits = ask_keysize (both? subkey_algo : algo, nbits);
4301           r = xmalloc_clear( sizeof *r + 20 );
4302           r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
4303           sprintf( r->u.value, "%u", nbits);
4304           r->next = para;
4305           para = r;
4306         }
4307
4308       xfree (curve);
4309     }
4310   else /* Default key generation.  */
4311     {
4312       int subalgo;
4313       unsigned int size, subsize;
4314       unsigned int keyuse, subkeyuse;
4315       const char *curve, *subcurve;
4316
4317       tty_printf ( _("Note: Use \"%s %s\""
4318                      " for a full featured key generation dialog.\n"),
4319 #if USE_GPG2_HACK
4320                    GPG_NAME "2"
4321 #else
4322                    GPG_NAME
4323 #endif
4324                    , "--full-generate-key" );
4325
4326       err = parse_key_parameter_string (NULL, -1,
4327                                         &algo, &size, &keyuse, &curve,
4328                                         &subalgo, &subsize,
4329                                         &subkeyuse, &subcurve);
4330       if (err)
4331         {
4332           log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
4333           return;
4334         }
4335       para = quickgen_set_para (para, 0, algo, size, curve, keyuse);
4336       if (subalgo)
4337         para = quickgen_set_para (para, 1,
4338                                   subalgo, subsize, subcurve, subkeyuse);
4339
4340
4341     }
4342
4343
4344   expire = full? ask_expire_interval (0, NULL)
4345                : parse_expire_string (default_expiration_interval);
4346   r = xcalloc (1, sizeof *r + 20);
4347   r->key = pKEYEXPIRE;
4348   r->u.expire = expire;
4349   r->next = para;
4350   para = r;
4351   r = xcalloc (1, sizeof *r + 20);
4352   r->key = pSUBKEYEXPIRE;
4353   r->u.expire = expire;
4354   r->next = para;
4355   para = r;
4356
4357   uid = ask_user_id (0, full, NULL);
4358   if (!uid)
4359     {
4360       log_error(_("Key generation canceled.\n"));
4361       release_parameter_list( para );
4362       return;
4363     }
4364   r = xcalloc (1, sizeof *r + strlen (uid));
4365   r->key = pUSERID;
4366   strcpy (r->u.value, uid);
4367   r->next = para;
4368   para = r;
4369
4370   proc_parameter_file (ctrl, para, "[internal]", &outctrl, !!card_serialno);
4371   release_parameter_list (para);
4372 }
4373
4374
4375 /* Create and delete a dummy packet to start off a list of kbnodes. */
4376 static void
4377 start_tree(KBNODE *tree)
4378 {
4379   PACKET *pkt;
4380
4381   pkt=xmalloc_clear(sizeof(*pkt));
4382   pkt->pkttype=PKT_NONE;
4383   *tree=new_kbnode(pkt);
4384   delete_kbnode(*tree);
4385 }
4386
4387
4388 /* Write the *protected* secret key to the file.  */
4389 static gpg_error_t
4390 card_write_key_to_backup_file (PKT_public_key *sk, const char *backup_dir)
4391 {
4392   gpg_error_t err = 0;
4393   int rc;
4394   char keyid_buffer[2 * 8 + 1];
4395   char name_buffer[50];
4396   char *fname;
4397   IOBUF fp;
4398   mode_t oldmask;
4399   PACKET *pkt = NULL;
4400
4401   format_keyid (pk_keyid (sk), KF_LONG, keyid_buffer, sizeof (keyid_buffer));
4402   snprintf (name_buffer, sizeof name_buffer, "sk_%s.gpg", keyid_buffer);
4403
4404   fname = make_filename (backup_dir, name_buffer, NULL);
4405   /* Note that the umask call is not anymore needed because
4406      iobuf_create now takes care of it.  However, it does not harm
4407      and thus we keep it.  */
4408   oldmask = umask (077);
4409   if (is_secured_filename (fname))
4410     {
4411       fp = NULL;
4412       gpg_err_set_errno (EPERM);
4413     }
4414   else
4415     fp = iobuf_create (fname, 1);
4416   umask (oldmask);
4417   if (!fp)
4418     {
4419       err = gpg_error_from_syserror ();
4420       log_error (_("can't create backup file '%s': %s\n"), fname, strerror (errno) );
4421       goto leave;
4422     }
4423
4424   pkt = xcalloc (1, sizeof *pkt);
4425   pkt->pkttype = PKT_SECRET_KEY;
4426   pkt->pkt.secret_key = sk;
4427
4428   rc = build_packet (fp, pkt);
4429   if (rc)
4430     {
4431       log_error ("build packet failed: %s\n", gpg_strerror (rc));
4432       iobuf_cancel (fp);
4433     }
4434   else
4435     {
4436       char *fprbuf;
4437
4438       iobuf_close (fp);
4439       iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
4440       log_info (_("Note: backup of card key saved to '%s'\n"), fname);
4441
4442       fprbuf = hexfingerprint (sk, NULL, 0);
4443       write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED, fprbuf,
4444                                     fname, strlen (fname), 0);
4445       xfree (fprbuf);
4446     }
4447
4448  leave:
4449   xfree (pkt);
4450   xfree (fname);
4451   return err;
4452 }
4453
4454
4455 /* Store key to card and make a backup file in OpenPGP format.  */
4456 static gpg_error_t
4457 card_store_key_with_backup (ctrl_t ctrl, PKT_public_key *sub_psk,
4458                             const char *backup_dir)
4459 {
4460   PKT_public_key *sk;
4461   gnupg_isotime_t timestamp;
4462   gpg_error_t err;
4463   char *hexgrip;
4464   int rc;
4465   struct agent_card_info_s info;
4466   gcry_cipher_hd_t cipherhd = NULL;
4467   char *cache_nonce = NULL;
4468   void *kek = NULL;
4469   size_t keklen;
4470
4471   sk = copy_public_key (NULL, sub_psk);
4472   if (!sk)
4473     return gpg_error_from_syserror ();
4474
4475   epoch2isotime (timestamp, (time_t)sk->timestamp);
4476   err = hexkeygrip_from_pk (sk, &hexgrip);
4477   if (err)
4478     return err;
4479
4480   memset(&info, 0, sizeof (info));
4481   rc = agent_scd_getattr ("SERIALNO", &info);
4482   if (rc)
4483     return (gpg_error_t)rc;
4484
4485   rc = agent_keytocard (hexgrip, 2, 1, info.serialno, timestamp);
4486   xfree (info.serialno);
4487   if (rc)
4488     {
4489       err = (gpg_error_t)rc;
4490       goto leave;
4491     }
4492
4493   err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
4494   if (err)
4495     {
4496       log_error ("error getting the KEK: %s\n", gpg_strerror (err));
4497       goto leave;
4498     }
4499
4500   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
4501                           GCRY_CIPHER_MODE_AESWRAP, 0);
4502   if (!err)
4503     err = gcry_cipher_setkey (cipherhd, kek, keklen);
4504   if (err)
4505     {
4506       log_error ("error setting up an encryption context: %s\n",
4507                  gpg_strerror (err));
4508       goto leave;
4509     }
4510
4511   err = receive_seckey_from_agent (ctrl, cipherhd, 0,
4512                                    &cache_nonce, hexgrip, sk);
4513   if (err)
4514     {
4515       log_error ("error getting secret key from agent: %s\n",
4516                  gpg_strerror (err));
4517       goto leave;
4518     }
4519
4520   err = card_write_key_to_backup_file (sk, backup_dir);
4521   if (err)
4522     log_error ("writing card key to backup file: %s\n", gpg_strerror (err));
4523   else
4524     /* Remove secret key data in agent side.  */
4525     agent_scd_learn (NULL, 1);
4526
4527  leave:
4528   xfree (cache_nonce);
4529   gcry_cipher_close (cipherhd);
4530   xfree (kek);
4531   xfree (hexgrip);
4532   free_public_key (sk);
4533   return err;
4534 }
4535
4536
4537 static void
4538 do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
4539                      struct output_control_s *outctrl, int card)
4540 {
4541   gpg_error_t err;
4542   KBNODE pub_root = NULL;
4543   const char *s;
4544   PKT_public_key *pri_psk = NULL;
4545   PKT_public_key *sub_psk = NULL;
4546   struct revocation_key *revkey;
4547   int did_sub = 0;
4548   u32 timestamp;
4549   char *cache_nonce = NULL;
4550
4551   if (outctrl->dryrun)
4552     {
4553       log_info("dry-run mode - key generation skipped\n");
4554       return;
4555     }
4556
4557   if ( outctrl->use_files )
4558     {
4559       if ( outctrl->pub.newfname )
4560         {
4561           iobuf_close(outctrl->pub.stream);
4562           outctrl->pub.stream = NULL;
4563           if (outctrl->pub.fname)
4564             iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
4565                          0, (char*)outctrl->pub.fname);
4566           xfree( outctrl->pub.fname );
4567           outctrl->pub.fname =  outctrl->pub.newfname;
4568           outctrl->pub.newfname = NULL;
4569
4570           if (is_secured_filename (outctrl->pub.fname) )
4571             {
4572               outctrl->pub.stream = NULL;
4573               gpg_err_set_errno (EPERM);
4574             }
4575           else
4576             outctrl->pub.stream = iobuf_create (outctrl->pub.fname, 0);
4577           if (!outctrl->pub.stream)
4578             {
4579               log_error(_("can't create '%s': %s\n"), outctrl->pub.newfname,
4580                         strerror(errno) );
4581               return;
4582             }
4583           if (opt.armor)
4584             {
4585               outctrl->pub.afx->what = 1;
4586               push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
4587             }
4588         }
4589       log_assert( outctrl->pub.stream );
4590       if (opt.verbose)
4591         log_info (_("writing public key to '%s'\n"), outctrl->pub.fname );
4592     }
4593
4594
4595   /* We create the packets as a tree of kbnodes.  Because the
4596      structure we create is known in advance we simply generate a
4597      linked list.  The first packet is a dummy packet which we flag as
4598      deleted.  The very first packet must always be a KEY packet.  */
4599
4600   start_tree (&pub_root);
4601
4602   timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
4603   if (!timestamp)
4604     timestamp = make_timestamp ();
4605
4606   /* Note that, depending on the backend (i.e. the used scdaemon
4607      version), the card key generation may update TIMESTAMP for each
4608      key.  Thus we need to pass TIMESTAMP to all signing function to
4609      make sure that the binding signature is done using the timestamp
4610      of the corresponding (sub)key and not that of the primary key.
4611      An alternative implementation could tell the signing function the
4612      node of the subkey but that is more work than just to pass the
4613      current timestamp.  */
4614
4615   if (!card)
4616     err = do_create (get_parameter_algo( para, pKEYTYPE, NULL ),
4617                      get_parameter_uint( para, pKEYLENGTH ),
4618                      get_parameter_value (para, pKEYCURVE),
4619                      pub_root,
4620                      timestamp,
4621                      get_parameter_u32( para, pKEYEXPIRE ), 0,
4622                      outctrl->keygen_flags,
4623                      get_parameter_passphrase (para),
4624                      &cache_nonce, NULL);
4625   else
4626     err = gen_card_key (1, get_parameter_algo( para, pKEYTYPE, NULL ),
4627                         1, pub_root, &timestamp,
4628                         get_parameter_u32 (para, pKEYEXPIRE));
4629
4630   /* Get the pointer to the generated public key packet.  */
4631   if (!err)
4632     {
4633       pri_psk = pub_root->next->pkt->pkt.public_key;
4634       log_assert (pri_psk);
4635
4636       /* Make sure a few fields are correctly set up before going
4637          further.  */
4638       pri_psk->flags.primary = 1;
4639       keyid_from_pk (pri_psk, NULL);
4640       /* We don't use pk_keyid to get keyid, because it also asserts
4641          that main_keyid is set!  */
4642       keyid_copy (pri_psk->main_keyid, pri_psk->keyid);
4643     }
4644
4645   if (!err && (revkey = get_parameter_revkey (para, pREVOKER)))
4646     err = write_direct_sig (pub_root, pri_psk, revkey, timestamp, cache_nonce);
4647
4648   if (!err && (s = get_parameter_value (para, pUSERID)))
4649     {
4650       write_uid (pub_root, s );
4651       err = write_selfsigs (pub_root, pri_psk,
4652                             get_parameter_uint (para, pKEYUSAGE), timestamp,
4653                             cache_nonce);
4654     }
4655
4656   /* Write the auth key to the card before the encryption key.  This
4657      is a partial workaround for a PGP bug (as of this writing, all
4658      versions including 8.1), that causes it to try and encrypt to
4659      the most recent subkey regardless of whether that subkey is
4660      actually an encryption type.  In this case, the auth key is an
4661      RSA key so it succeeds. */
4662
4663   if (!err && card && get_parameter (para, pAUTHKEYTYPE))
4664     {
4665       err = gen_card_key (3, get_parameter_algo( para, pAUTHKEYTYPE, NULL ),
4666                           0, pub_root, &timestamp,
4667                           get_parameter_u32 (para, pKEYEXPIRE));
4668       if (!err)
4669         err = write_keybinding (pub_root, pri_psk, NULL,
4670                                 PUBKEY_USAGE_AUTH, timestamp, cache_nonce);
4671     }
4672
4673   if (!err && get_parameter (para, pSUBKEYTYPE))
4674     {
4675       sub_psk = NULL;
4676       s = NULL;
4677       if (!card || (s = get_parameter_value (para, pCARDBACKUPKEY)))
4678         {
4679           err = do_create (get_parameter_algo (para, pSUBKEYTYPE, NULL),
4680                            get_parameter_uint (para, pSUBKEYLENGTH),
4681                            get_parameter_value (para, pSUBKEYCURVE),
4682                            pub_root,
4683                            timestamp,
4684                            get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
4685                            s ? KEYGEN_FLAG_NO_PROTECTION : outctrl->keygen_flags,
4686                            get_parameter_passphrase (para),
4687                            &cache_nonce, NULL);
4688           /* Get the pointer to the generated public subkey packet.  */
4689           if (!err)
4690             {
4691               kbnode_t node;
4692
4693               for (node = pub_root; node; node = node->next)
4694                 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4695                   sub_psk = node->pkt->pkt.public_key;
4696               log_assert (sub_psk);
4697
4698               if (s)
4699                 err = card_store_key_with_backup (ctrl,
4700                                                   sub_psk, gnupg_homedir ());
4701             }
4702         }
4703       else
4704         {
4705           err = gen_card_key (2, get_parameter_algo (para, pSUBKEYTYPE, NULL),
4706                               0, pub_root, &timestamp,
4707                               get_parameter_u32 (para, pKEYEXPIRE));
4708         }
4709
4710       if (!err)
4711         err = write_keybinding (pub_root, pri_psk, sub_psk,
4712                                 get_parameter_uint (para, pSUBKEYUSAGE),
4713                                 timestamp, cache_nonce);
4714       did_sub = 1;
4715     }
4716
4717   if (!err && outctrl->use_files)  /* Direct write to specified files.  */
4718     {
4719       err = write_keyblock (outctrl->pub.stream, pub_root);
4720       if (err)
4721         log_error ("can't write public key: %s\n", gpg_strerror (err));
4722     }
4723   else if (!err) /* Write to the standard keyrings.  */
4724     {
4725       KEYDB_HANDLE pub_hd;
4726
4727       pub_hd = keydb_new ();
4728       if (!pub_hd)
4729         err = gpg_error_from_syserror ();
4730       else
4731         {
4732           err = keydb_locate_writable (pub_hd);
4733           if (err)
4734             log_error (_("no writable public keyring found: %s\n"),
4735                        gpg_strerror (err));
4736         }
4737
4738       if (!err && opt.verbose)
4739         {
4740           log_info (_("writing public key to '%s'\n"),
4741                     keydb_get_resource_name (pub_hd));
4742         }
4743
4744       if (!err)
4745         {
4746           err = keydb_insert_keyblock (pub_hd, pub_root);
4747           if (err)
4748             log_error (_("error writing public keyring '%s': %s\n"),
4749                        keydb_get_resource_name (pub_hd), gpg_strerror (err));
4750         }
4751
4752       keydb_release (pub_hd);
4753
4754       if (!err)
4755         {
4756           int no_enc_rsa;
4757           PKT_public_key *pk;
4758
4759           no_enc_rsa = ((get_parameter_algo (para, pKEYTYPE, NULL)
4760                          == PUBKEY_ALGO_RSA)
4761                         && get_parameter_uint (para, pKEYUSAGE)
4762                         && !((get_parameter_uint (para, pKEYUSAGE)
4763                               & PUBKEY_USAGE_ENC)) );
4764
4765           pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4766
4767           keyid_from_pk (pk, pk->main_keyid);
4768           register_trusted_keyid (pk->main_keyid);
4769
4770           update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
4771                                   | TRUST_ULTIMATE ));
4772
4773           gen_standard_revoke (pk, cache_nonce);
4774
4775           /* Get rid of the first empty packet.  */
4776           commit_kbnode (&pub_root);
4777
4778           if (!opt.batch)
4779             {
4780               tty_printf (_("public and secret key created and signed.\n") );
4781               tty_printf ("\n");
4782               merge_keys_and_selfsig (pub_root);
4783               list_keyblock_direct (ctrl, pub_root, 0, 1, 1, 1);
4784             }
4785
4786
4787           if (!opt.batch
4788               && (get_parameter_algo (para, pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
4789                   || no_enc_rsa )
4790               && !get_parameter (para, pSUBKEYTYPE) )
4791             {
4792               tty_printf(_("Note that this key cannot be used for "
4793                            "encryption.  You may want to use\n"
4794                            "the command \"--edit-key\" to generate a "
4795                            "subkey for this purpose.\n") );
4796             }
4797         }
4798     }
4799
4800   if (err)
4801     {
4802       if (opt.batch)
4803         log_error ("key generation failed: %s\n", gpg_strerror (err) );
4804       else
4805         tty_printf (_("Key generation failed: %s\n"), gpg_strerror (err) );
4806       write_status_error (card? "card_key_generate":"key_generate", err);
4807       print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
4808     }
4809   else
4810     {
4811       PKT_public_key *pk = find_kbnode (pub_root,
4812                                         PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4813       print_status_key_created (did_sub? 'B':'P', pk,
4814                                 get_parameter_value (para, pHANDLE));
4815     }
4816
4817   release_kbnode (pub_root);
4818   xfree (cache_nonce);
4819 }
4820
4821
4822 static gpg_error_t
4823 parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
4824                          const char *algostr, const char *usagestr,
4825                          const char *expirestr,
4826                          int *r_algo, unsigned int *r_usage, u32 *r_expire,
4827                          unsigned int *r_nbits, char **r_curve)
4828 {
4829   gpg_error_t err;
4830   int algo;
4831   unsigned int use, nbits;
4832   u32 expire;
4833   int wantuse;
4834   const char *curve = NULL;
4835
4836   *r_curve = NULL;
4837
4838   nbits = 0;
4839
4840   /* Parse the algo string.  */
4841   if (algostr && *algostr == '&' && strlen (algostr) == 41)
4842     {
4843       /* Take algo from existing key.  */
4844       algo = check_keygrip (ctrl, algostr+1);
4845       /* FIXME: We need the curve name as well.  */
4846       return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
4847     }
4848
4849   err = parse_key_parameter_string (algostr, for_subkey? 1 : 0,
4850                                     &algo, &nbits, &use, &curve,
4851                                     NULL, NULL, NULL, NULL);
4852   if (err)
4853     return err;
4854
4855   /* Parse the usage string.  */
4856   if (!usagestr || !*usagestr
4857       || !strcmp (usagestr, "default") || !strcmp (usagestr, "-"))
4858     ; /* Keep usage from parse_key_parameter_string.  */
4859   else if ((wantuse = parse_usagestr (usagestr)) != -1)
4860     use = wantuse;
4861   else
4862     return gpg_error (GPG_ERR_INV_VALUE);
4863
4864   /* Make sure a primary key has the CERT usage.  */
4865   if (!for_subkey)
4866     use |= PUBKEY_USAGE_CERT;
4867
4868   /* Check that usage is possible.  NB: We have the same check in
4869    * parse_key_parameter_string but need it here again in case the
4870    * separate usage value has been given. */
4871   if (/**/((use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
4872            && !pubkey_get_nsig (algo))
4873        || ((use & PUBKEY_USAGE_ENC)
4874            && !pubkey_get_nenc (algo))
4875        || (for_subkey && (use & PUBKEY_USAGE_CERT)))
4876     return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
4877
4878   /* Parse the expire string.  */
4879   expire = parse_expire_string (expirestr);
4880   if (expire == (u32)-1 )
4881     return gpg_error (GPG_ERR_INV_VALUE);
4882
4883   if (curve)
4884     {
4885       *r_curve = xtrystrdup (curve);
4886       if (!*r_curve)
4887         return gpg_error_from_syserror ();
4888     }
4889   *r_algo = algo;
4890   *r_usage = use;
4891   *r_expire = expire;
4892   *r_nbits = nbits;
4893   return 0;
4894 }
4895
4896
4897 /* Add a new subkey to an existing key.  Returns 0 if a new key has
4898    been generated and put into the keyblocks.  If any of ALGOSTR,
4899    USAGESTR, or EXPIRESTR is NULL interactive mode is used. */
4900 gpg_error_t
4901 generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock, const char *algostr,
4902                      const char *usagestr, const char *expirestr)
4903 {
4904   gpg_error_t err = 0;
4905   int interactive;
4906   kbnode_t node;
4907   PKT_public_key *pri_psk = NULL;
4908   PKT_public_key *sub_psk = NULL;
4909   int algo;
4910   unsigned int use;
4911   u32 expire;
4912   unsigned int nbits = 0;
4913   char *curve = NULL;
4914   u32 cur_time;
4915   char *key_from_hexgrip = NULL;
4916   char *hexgrip = NULL;
4917   char *serialno = NULL;
4918   char *cache_nonce = NULL;
4919   char *passwd_nonce = NULL;
4920
4921   interactive = (!algostr || !usagestr || !expirestr);
4922
4923   /* Break out the primary key.  */
4924   node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
4925   if (!node)
4926     {
4927       log_error ("Oops; primary key missing in keyblock!\n");
4928       err = gpg_error (GPG_ERR_BUG);
4929       goto leave;
4930     }
4931   pri_psk = node->pkt->pkt.public_key;
4932
4933   cur_time = make_timestamp ();
4934
4935   if (pri_psk->timestamp > cur_time)
4936     {
4937       ulong d = pri_psk->timestamp - cur_time;
4938       log_info ( d==1 ? _("key has been created %lu second "
4939                           "in future (time warp or clock problem)\n")
4940                  : _("key has been created %lu seconds "
4941                      "in future (time warp or clock problem)\n"), d );
4942       if (!opt.ignore_time_conflict)
4943         {
4944           err = gpg_error (GPG_ERR_TIME_CONFLICT);
4945           goto leave;
4946         }
4947     }
4948
4949   if (pri_psk->version < 4)
4950     {
4951       log_info (_("Note: creating subkeys for v3 keys "
4952                   "is not OpenPGP compliant\n"));
4953       err = gpg_error (GPG_ERR_CONFLICT);
4954       goto leave;
4955     }
4956
4957   err = hexkeygrip_from_pk (pri_psk, &hexgrip);
4958   if (err)
4959     goto leave;
4960   if (agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
4961     {
4962       if (interactive)
4963         tty_printf (_("Secret parts of primary key are not available.\n"));
4964       else
4965         log_info (  _("Secret parts of primary key are not available.\n"));
4966       err = gpg_error (GPG_ERR_NO_SECKEY);
4967       goto leave;
4968     }
4969   if (serialno)
4970     {
4971       if (interactive)
4972         tty_printf (_("Secret parts of primary key are stored on-card.\n"));
4973       else
4974         log_info (  _("Secret parts of primary key are stored on-card.\n"));
4975     }
4976
4977   if (interactive)
4978     {
4979       algo = ask_algo (ctrl, 1, NULL, &use, &key_from_hexgrip);
4980       log_assert (algo);
4981
4982       if (key_from_hexgrip)
4983         nbits = 0;
4984       else if (algo == PUBKEY_ALGO_ECDSA
4985                || algo == PUBKEY_ALGO_EDDSA
4986                || algo == PUBKEY_ALGO_ECDH)
4987         curve = ask_curve (&algo, NULL);
4988       else
4989         nbits = ask_keysize (algo, 0);
4990
4991       expire = ask_expire_interval (0, NULL);
4992       if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
4993                                                    _("Really create? (y/N) ")))
4994         {
4995           err = gpg_error (GPG_ERR_CANCELED);
4996           goto leave;
4997         }
4998     }
4999   else /* Unattended mode.  */
5000     {
5001       err = parse_algo_usage_expire (ctrl, 1, algostr, usagestr, expirestr,
5002                                      &algo, &use, &expire, &nbits, &curve);
5003       if (err)
5004         goto leave;
5005     }
5006
5007   /* Verify the passphrase now so that we get a cache item for the
5008    * primary key passphrase.  The agent also returns a passphrase
5009    * nonce, which we can use to set the passphrase for the subkey to
5010    * that of the primary key.  */
5011   {
5012     char *desc = gpg_format_keydesc (pri_psk, FORMAT_KEYDESC_NORMAL, 1);
5013     err = agent_passwd (ctrl, hexgrip, desc, 1 /*=verify*/,
5014                         &cache_nonce, &passwd_nonce);
5015     xfree (desc);
5016   }
5017
5018   /* Start creation.  */
5019   if (key_from_hexgrip)
5020     {
5021       err = do_create_from_keygrip (ctrl, algo, key_from_hexgrip,
5022                                     keyblock, cur_time, expire, 1);
5023     }
5024   else
5025     {
5026       const char *passwd;
5027
5028       /* If the pinentry loopback mode is not and we have a static
5029          passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
5030          mode), we use that passphrase for the new subkey.  */
5031       if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
5032           && have_static_passphrase ())
5033         passwd = get_static_passphrase ();
5034       else
5035         passwd = NULL;
5036
5037       err = do_create (algo, nbits, curve,
5038                        keyblock, cur_time, expire, 1, 0,
5039                        passwd, &cache_nonce, &passwd_nonce);
5040     }
5041   if (err)
5042     goto leave;
5043
5044   /* Get the pointer to the generated public subkey packet.  */
5045   for (node = keyblock; node; node = node->next)
5046     if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5047       sub_psk = node->pkt->pkt.public_key;
5048
5049   /* Write the binding signature.  */
5050   err = write_keybinding (keyblock, pri_psk, sub_psk, use, cur_time,
5051                           cache_nonce);
5052   if (err)
5053     goto leave;
5054
5055   print_status_key_created ('S', sub_psk, NULL);
5056
5057
5058  leave:
5059   xfree (key_from_hexgrip);
5060   xfree (curve);
5061   xfree (hexgrip);
5062   xfree (serialno);
5063   xfree (cache_nonce);
5064   xfree (passwd_nonce);
5065   if (err)
5066     log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
5067   return err;
5068 }
5069
5070
5071 #ifdef ENABLE_CARD_SUPPORT
5072 /* Generate a subkey on a card. */
5073 gpg_error_t
5074 generate_card_subkeypair (kbnode_t pub_keyblock,
5075                           int keyno, const char *serialno)
5076 {
5077   gpg_error_t err = 0;
5078   kbnode_t node;
5079   PKT_public_key *pri_pk = NULL;
5080   unsigned int use;
5081   u32 expire;
5082   u32 cur_time;
5083   struct para_data_s *para = NULL;
5084   PKT_public_key *sub_pk = NULL;
5085   int algo;
5086   struct agent_card_info_s info;
5087
5088   log_assert (keyno >= 1 && keyno <= 3);
5089
5090   memset (&info, 0, sizeof (info));
5091   err = agent_scd_getattr ("KEY-ATTR", &info);
5092   if (err)
5093     {
5094       log_error (_("error getting current key info: %s\n"), gpg_strerror (err));
5095       return err;
5096     }
5097   algo = info.key_attr[keyno-1].algo;
5098
5099   para = xtrycalloc (1, sizeof *para + strlen (serialno) );
5100   if (!para)
5101     {
5102       err = gpg_error_from_syserror ();
5103       goto leave;
5104     }
5105   para->key = pSERIALNO;
5106   strcpy (para->u.value, serialno);
5107
5108   /* Break out the primary secret key */
5109   node = find_kbnode (pub_keyblock, PKT_PUBLIC_KEY);
5110   if (!node)
5111     {
5112       log_error ("Oops; publkic key lost!\n");
5113       err = gpg_error (GPG_ERR_INTERNAL);
5114       goto leave;
5115     }
5116   pri_pk = node->pkt->pkt.public_key;
5117
5118   cur_time = make_timestamp();
5119   if (pri_pk->timestamp > cur_time)
5120     {
5121       ulong d = pri_pk->timestamp - cur_time;
5122       log_info (d==1 ? _("key has been created %lu second "
5123                          "in future (time warp or clock problem)\n")
5124                      : _("key has been created %lu seconds "
5125                          "in future (time warp or clock problem)\n"), d );
5126         if (!opt.ignore_time_conflict)
5127           {
5128             err = gpg_error (GPG_ERR_TIME_CONFLICT);
5129             goto leave;
5130           }
5131     }
5132
5133   if (pri_pk->version < 4)
5134     {
5135       log_info (_("Note: creating subkeys for v3 keys "
5136                   "is not OpenPGP compliant\n"));
5137       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
5138       goto leave;
5139     }
5140
5141   expire = ask_expire_interval (0, NULL);
5142   if (keyno == 1)
5143     use = PUBKEY_USAGE_SIG;
5144   else if (keyno == 2)
5145     use = PUBKEY_USAGE_ENC;
5146   else
5147     use = PUBKEY_USAGE_AUTH;
5148   if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
5149                                                _("Really create? (y/N) ")))
5150     {
5151       err = gpg_error (GPG_ERR_CANCELED);
5152       goto leave;
5153     }
5154
5155   /* Note, that depending on the backend, the card key generation may
5156      update CUR_TIME.  */
5157   err = gen_card_key (keyno, algo, 0, pub_keyblock, &cur_time, expire);
5158   /* Get the pointer to the generated public subkey packet.  */
5159   if (!err)
5160     {
5161       for (node = pub_keyblock; node; node = node->next)
5162         if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5163           sub_pk = node->pkt->pkt.public_key;
5164       log_assert (sub_pk);
5165       err = write_keybinding (pub_keyblock, pri_pk, sub_pk,
5166                               use, cur_time, NULL);
5167     }
5168
5169  leave:
5170   if (err)
5171     log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
5172   else
5173     print_status_key_created ('S', sub_pk, NULL);
5174   release_parameter_list (para);
5175   return err;
5176 }
5177 #endif /* !ENABLE_CARD_SUPPORT */
5178
5179 /*
5180  * Write a keyblock to an output stream
5181  */
5182 static int
5183 write_keyblock( IOBUF out, KBNODE node )
5184 {
5185   for( ; node ; node = node->next )
5186     {
5187       if(!is_deleted_kbnode(node))
5188         {
5189           int rc = build_packet( out, node->pkt );
5190           if( rc )
5191             {
5192               log_error("build_packet(%d) failed: %s\n",
5193                         node->pkt->pkttype, gpg_strerror (rc) );
5194               return rc;
5195             }
5196         }
5197     }
5198
5199   return 0;
5200 }
5201
5202
5203 /* Note that timestamp is an in/out arg. */
5204 static gpg_error_t
5205 gen_card_key (int keyno, int algo, int is_primary, kbnode_t pub_root,
5206               u32 *timestamp, u32 expireval)
5207 {
5208 #ifdef ENABLE_CARD_SUPPORT
5209   gpg_error_t err;
5210   PACKET *pkt;
5211   PKT_public_key *pk;
5212   char keyid[10];
5213   unsigned char *public;
5214   gcry_sexp_t s_key;
5215
5216   snprintf (keyid, DIM(keyid), "OPENPGP.%d", keyno);
5217
5218   pk = xtrycalloc (1, sizeof *pk );
5219   if (!pk)
5220     return gpg_error_from_syserror ();
5221   pkt = xtrycalloc (1, sizeof *pkt);
5222   if (!pkt)
5223     {
5224       xfree (pk);
5225       return gpg_error_from_syserror ();
5226     }
5227
5228   /* Note: SCD knows the serialnumber, thus there is no point in passing it.  */
5229   err = agent_scd_genkey (keyno, 1, timestamp);
5230   /*  The code below is not used because we force creation of
5231    *  the a card key (3rd arg).
5232    * if (gpg_err_code (rc) == GPG_ERR_EEXIST)
5233    *   {
5234    *     tty_printf ("\n");
5235    *     log_error ("WARNING: key does already exists!\n");
5236    *     tty_printf ("\n");
5237    *     if ( cpr_get_answer_is_yes( "keygen.card.replace_key",
5238    *                                 _("Replace existing key? ")))
5239    *       rc = agent_scd_genkey (keyno, 1, timestamp);
5240    *   }
5241   */
5242   if (err)
5243     {
5244       log_error ("key generation failed: %s\n", gpg_strerror (err));
5245       xfree (pkt);
5246       xfree (pk);
5247       return err;
5248     }
5249
5250   /* Send the READKEY command so that the agent creates a shadow key for
5251      card key.  We need to do that now so that we are able to create
5252      the self-signatures. */
5253   err = agent_readkey (NULL, 1, keyid, &public);
5254   if (err)
5255     return err;
5256   err = gcry_sexp_sscan (&s_key, NULL, public,
5257                          gcry_sexp_canon_len (public, 0, NULL, NULL));
5258   xfree (public);
5259   if (err)
5260     return err;
5261
5262   if (algo == PUBKEY_ALGO_RSA)
5263     err = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
5264   else if (algo == PUBKEY_ALGO_ECDSA
5265            || algo == PUBKEY_ALGO_EDDSA
5266            || algo == PUBKEY_ALGO_ECDH )
5267     err = ecckey_from_sexp (pk->pkey, s_key, algo);
5268   else
5269     err = gpg_error (GPG_ERR_PUBKEY_ALGO);
5270   gcry_sexp_release (s_key);
5271
5272   if (err)
5273     {
5274       log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
5275       free_public_key (pk);
5276       return err;
5277     }
5278
5279   pk->timestamp = *timestamp;
5280   pk->version = 4;
5281   if (expireval)
5282     pk->expiredate = pk->timestamp + expireval;
5283   pk->pubkey_algo = algo;
5284
5285   pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
5286   pkt->pkt.public_key = pk;
5287   add_kbnode (pub_root, new_kbnode (pkt));
5288
5289   return 0;
5290 #else
5291   (void)keyno;
5292   (void)is_primary;
5293   (void)pub_root;
5294   (void)timestamp;
5295   (void)expireval;
5296   return gpg_error (GPG_ERR_NOT_SUPPORTED);
5297 #endif /*!ENABLE_CARD_SUPPORT*/
5298 }