LCOV - code coverage report
Current view: top level - g10 - keygen.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 611 2122 28.8 %
Date: 2015-11-05 17:10:59 Functions: 38 67 56.7 %

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

Generated by: LCOV version 1.11