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