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