~ubuntu-branches/ubuntu/feisty/gnupg2/feisty

« back to all changes in this revision

Viewing changes to g10/keygen.c

  • Committer: Bazaar Package Importer
  • Author(s): Jonathan Riddell
  • Date: 2006-07-11 11:38:13 UTC
  • mfrom: (1.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20060711113813-zaw7unlbuh7gyxtl
Tags: 1.9.21-0ubuntu1
New upstream release

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* keygen.c - generate a key pair
2
 
 * Copyright (C) 1998, 1999, 2000, 2001, 2002,
3
 
 *               2003, 2004 Free Software Foundation, Inc.
 
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
 
3
 *               2006 Free Software Foundation, Inc.
4
4
 *
5
5
 * This file is part of GnuPG.
6
6
 *
16
16
 *
17
17
 * You should have received a copy of the GNU General Public License
18
18
 * along with this program; if not, write to the Free Software
19
 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
 
20
 * USA.
20
21
 */
21
22
 
22
23
#include <config.h>
26
27
#include <ctype.h>
27
28
#include <errno.h>
28
29
#include <assert.h>
 
30
#include <sys/types.h>
 
31
#include <sys/stat.h>
 
32
#include <unistd.h>
29
33
 
30
34
#include "gpg.h"
31
35
#include "util.h"
63
67
  pPASSPHRASE,
64
68
  pPASSPHRASE_DEK,
65
69
  pPASSPHRASE_S2K,
66
 
  pSERIALNO
 
70
  pSERIALNO,
 
71
  pBACKUPENCDIR,
 
72
  pHANDLE
67
73
};
68
74
 
69
75
struct para_data_s {
87
93
    struct {
88
94
        char  *fname;
89
95
        char  *newfname;
90
 
        iobuf_t stream;
 
96
        IOBUF stream;
91
97
        armor_filter_context_t afx;
92
98
    } pub;
93
99
    struct {
94
100
        char  *fname;
95
101
        char  *newfname;
96
 
        iobuf_t stream;
 
102
        IOBUF stream;
97
103
        armor_filter_context_t afx;
98
104
    } sec;
99
105
};
115
121
static int mdc_available,ks_modify;
116
122
 
117
123
static void do_generate_keypair( struct para_data_s *para,
118
 
                                 struct output_control_s *outctrl, int card);
119
 
static int write_keyblock( iobuf_t out, KBNODE node );
120
 
static int gen_card_key (int algo, int keyno, KBNODE pub_root, KBNODE sec_root,
 
124
                                 struct output_control_s *outctrl, int card );
 
125
static int  write_keyblock( IOBUF out, KBNODE node );
 
126
static int gen_card_key (int algo, int keyno, int is_primary,
 
127
                         KBNODE pub_root, KBNODE sec_root,
121
128
                         u32 expireval, struct para_data_s *para);
 
129
static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
 
130
                                     KBNODE pub_root, KBNODE sec_root,
 
131
                                     u32 expireval, struct para_data_s *para,
 
132
                                     const char *backup_dir);
 
133
 
 
134
 
 
135
static void
 
136
print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
 
137
{
 
138
  byte array[MAX_FINGERPRINT_LEN], *s;
 
139
  char *buf, *p;
 
140
  size_t i, n;
 
141
  
 
142
  if (!handle)
 
143
    handle = "";
 
144
 
 
145
  buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
 
146
 
 
147
  p = buf;
 
148
  if (letter || pk)
 
149
    {
 
150
      *p++ = letter;
 
151
      *p++ = ' ';
 
152
      fingerprint_from_pk (pk, array, &n);
 
153
      s = array;
 
154
      for (i=0; i < n ; i++, s++, p += 2)
 
155
        sprintf (p, "%02X", *s);
 
156
    }
 
157
  if (*handle)
 
158
    {
 
159
      *p++ = ' ';
 
160
      for (i=0; handle[i] && i < 100; i++)
 
161
        *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
 
162
    }
 
163
  *p = 0;
 
164
  write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
 
165
                     buf);
 
166
  xfree (buf);
 
167
}
 
168
 
 
169
static void
 
170
print_status_key_not_created (const char *handle)
 
171
{
 
172
  print_status_key_created (0, NULL, handle);
 
173
}
122
174
 
123
175
 
124
176
 
125
177
static void
126
178
write_uid( KBNODE root, const char *s )
127
179
{
128
 
    PACKET *pkt = xcalloc (1,sizeof *pkt );
 
180
    PACKET *pkt = xmalloc_clear(sizeof *pkt );
129
181
    size_t n = strlen(s);
130
182
 
131
183
    pkt->pkttype = PKT_USER_ID;
132
 
    pkt->pkt.user_id = xcalloc (1, sizeof *pkt->pkt.user_id + n - 1 );
 
184
    pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
133
185
    pkt->pkt.user_id->len = n;
134
186
    pkt->pkt.user_id->ref = 1;
135
187
    strcpy(pkt->pkt.user_id->name, s);
141
193
{
142
194
    byte buf[1];
143
195
 
144
 
    if (!use) 
145
 
        return;
146
 
 
147
196
    buf[0] = 0;
 
197
 
 
198
    /* The spec says that all primary keys MUST be able to certify. */
 
199
    if(sig->sig_class!=0x18)
 
200
      buf[0] |= 0x01;
 
201
 
148
202
    if (use & PUBKEY_USAGE_SIG)
149
 
      {
150
 
        if(sig->sig_class==0x18)
151
 
          buf[0] |= 0x02; /* Don't set the certify flag for subkeys */
152
 
        else
153
 
          buf[0] |= 0x01 | 0x02;
154
 
      }
 
203
      buf[0] |= 0x02;
155
204
    if (use & PUBKEY_USAGE_ENC)
156
205
        buf[0] |= 0x04 | 0x08;
157
206
    if (use & PUBKEY_USAGE_AUTH)
158
207
        buf[0] |= 0x20;
 
208
 
 
209
    if (!buf[0]) 
 
210
        return;
 
211
 
159
212
    build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
160
213
}
161
214
 
228
281
    return 0;
229
282
}
230
283
 
231
 
#ifdef USE_AES
232
 
#define AES "S9 S8 S7 "
233
 
#else
234
 
#define AES ""
235
 
#endif
236
 
 
237
 
#ifdef USE_CAST5
238
 
#define CAST5 "S3 "
239
 
#else
240
 
#define CAST5 ""
241
 
#endif
242
 
 
243
284
/*
244
285
 * Parse the supplied string and use it to set the standard
245
286
 * preferences.  The string may be in a form like the one printed by
253
294
    byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
254
295
    int nsym=0, nhash=0, nzip=0, val, rc=0;
255
296
    int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
256
 
 
257
 
    if (!string || !ascii_strcasecmp (string, "default")) {
258
 
      if (opt.def_preference_list)
259
 
        string=opt.def_preference_list;
260
 
      else if ( !openpgp_cipher_test_algo(CIPHER_ALGO_IDEA) )
261
 
        string = AES CAST5 "S2 S1 H2 H3 Z2 Z1";
262
 
      else
263
 
        string = AES CAST5 "S2 H2 H3 Z2 Z1";
264
 
 
265
 
      /* If we have it, IDEA goes *after* 3DES so it won't be used
266
 
         unless we're encrypting along with a V3 key.  Ideally, we
267
 
         would only put the S1 preference in if the key was RSA and
268
 
         <=2048 bits, as that is what won't break PGP2, but that is
269
 
         difficult with the current code, and not really worth
270
 
         checking as a non-RSA <=2048 bit key wouldn't be usable by
271
 
         PGP2 anyway. -dms */
272
 
    }
 
297
    char dummy_string[45+1]; /* Enough for 15 items. */
 
298
 
 
299
    if (!string || !ascii_strcasecmp (string, "default"))
 
300
      {
 
301
        if (opt.def_preference_list)
 
302
          string=opt.def_preference_list;
 
303
        else
 
304
          {
 
305
            dummy_string[0]='\0';
 
306
 
 
307
            /* The rationale why we use the order AES256,192,128 is
 
308
               for compatibility reasons with PGP.  If gpg would
 
309
               define AES128 first, we would get the somewhat
 
310
               confusing situation:
 
311
 
 
312
                 gpg -r pgpkey -r gpgkey  ---gives--> AES256
 
313
                 gpg -r gpgkey -r pgpkey  ---gives--> AES
 
314
                 
 
315
               Note that by using --personal-cipher-preferences it is
 
316
               possible to prefer AES128.
 
317
            */
 
318
 
 
319
            /* Make sure we do not add more than 15 items here, as we
 
320
               could overflow the size of dummy_string.  We currently
 
321
               have at most 12. */
 
322
            if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
 
323
              strcat(dummy_string,"S9 ");
 
324
            if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
 
325
              strcat(dummy_string,"S8 ");
 
326
            if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
 
327
              strcat(dummy_string,"S7 ");
 
328
            if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
 
329
              strcat(dummy_string,"S3 ");
 
330
            strcat(dummy_string,"S2 "); /* 3DES */
 
331
            /* If we have it, IDEA goes *after* 3DES so it won't be
 
332
               used unless we're encrypting along with a V3 key.
 
333
               Ideally, we would only put the S1 preference in if the
 
334
               key was RSA and <=2048 bits, as that is what won't
 
335
               break PGP2, but that is difficult with the current
 
336
               code, and not really worth checking as a non-RSA <=2048
 
337
               bit key wouldn't be usable by PGP2 anyway. -dms */
 
338
            if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
 
339
              strcat(dummy_string,"S1 ");
 
340
 
 
341
            /* SHA-1 */
 
342
            strcat(dummy_string,"H2 ");
 
343
 
 
344
            if (!openpgp_md_test_algo(DIGEST_ALGO_SHA256))
 
345
              strcat(dummy_string,"H8 ");
 
346
 
 
347
            /* RIPEMD160 */
 
348
            strcat(dummy_string,"H3 ");
 
349
 
 
350
            /* ZLIB */
 
351
            strcat(dummy_string,"Z2 ");
 
352
 
 
353
            if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
 
354
              strcat(dummy_string,"Z3 ");
 
355
 
 
356
            /* ZIP */
 
357
            strcat(dummy_string,"Z1");
 
358
 
 
359
            string=dummy_string;
 
360
          }
 
361
      }
273
362
    else if (!ascii_strcasecmp (string, "none"))
274
363
        string = "";
275
364
 
277
366
      {
278
367
        char *tok,*prefstring;
279
368
 
280
 
        prefstring=xstrdup (string); /* need a writable string! */
 
369
        prefstring=xstrdup(string); /* need a writable string! */
281
370
 
282
371
        while((tok=strsep(&prefstring," ,")))
283
372
          {
284
 
            if((val=openpgp_cipher_map_name(tok)))
 
373
            if((val=string_to_cipher_algo (tok)))
285
374
              {
286
375
                if(set_one_pref(val,1,tok,sym,&nsym))
287
376
                  rc=-1;
288
377
              }
289
 
            else if((val=openpgp_md_map_name(tok)))
 
378
            else if((val=string_to_digest_algo (tok)))
290
379
              {
291
380
                if(set_one_pref(val,2,tok,hash,&nhash))
292
381
                  rc=-1;
317
406
              }
318
407
          }
319
408
 
320
 
        xfree (prefstring);
 
409
        xfree(prefstring);
321
410
      }
322
411
 
323
412
    if(!rc)
326
415
          {
327
416
            if(personal==PREFTYPE_SYM)
328
417
              {
329
 
                xfree (opt.personal_cipher_prefs);
 
418
                xfree(opt.personal_cipher_prefs);
330
419
 
331
420
                if(nsym==0)
332
421
                  opt.personal_cipher_prefs=NULL;
335
424
                    int i;
336
425
 
337
426
                    opt.personal_cipher_prefs=
338
 
                      xmalloc (sizeof(prefitem_t *)*(nsym+1));
 
427
                      xmalloc(sizeof(prefitem_t *)*(nsym+1));
339
428
 
340
429
                    for (i=0; i<nsym; i++)
341
430
                      {
349
438
              }
350
439
            else if(personal==PREFTYPE_HASH)
351
440
              {
352
 
                xfree (opt.personal_digest_prefs);
 
441
                xfree(opt.personal_digest_prefs);
353
442
 
354
443
                if(nhash==0)
355
444
                  opt.personal_digest_prefs=NULL;
358
447
                    int i;
359
448
 
360
449
                    opt.personal_digest_prefs=
361
 
                      xmalloc (sizeof(prefitem_t *)*(nhash+1));
 
450
                      xmalloc(sizeof(prefitem_t *)*(nhash+1));
362
451
 
363
452
                    for (i=0; i<nhash; i++)
364
453
                      {
372
461
              }
373
462
            else if(personal==PREFTYPE_ZIP)
374
463
              {
375
 
                xfree (opt.personal_compress_prefs);
 
464
                xfree(opt.personal_compress_prefs);
376
465
 
377
466
                if(nzip==0)
378
467
                  opt.personal_compress_prefs=NULL;
381
470
                    int i;
382
471
 
383
472
                    opt.personal_compress_prefs=
384
 
                      xmalloc (sizeof(prefitem_t *)*(nzip+1));
 
473
                      xmalloc(sizeof(prefitem_t *)*(nzip+1));
385
474
 
386
475
                    for (i=0; i<nzip; i++)
387
476
                      {
408
497
    return rc;
409
498
}
410
499
 
411
 
#undef CAST5
412
 
#undef AES
413
 
 
414
500
/* Return a fake user ID containing the preferences.  Caller must
415
501
   free. */
416
502
PKT_user_id *keygen_get_std_prefs(void)
417
503
{
418
504
  int i,j=0;
419
 
  PKT_user_id *uid=xcalloc (1,sizeof(PKT_user_id));
 
505
  PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
420
506
 
421
507
  if(!prefs_initialized)
422
508
    keygen_set_std_prefs(NULL,0);
423
509
 
424
 
  uid->prefs=xmalloc ((sizeof(prefitem_t *)*
 
510
  uid->ref=1;
 
511
 
 
512
  uid->prefs=xmalloc((sizeof(prefitem_t *)*
425
513
                      (nsym_prefs+nhash_prefs+nzip_prefs+1)));
426
514
 
427
515
  for(i=0;i<nsym_prefs;i++,j++)
445
533
  uid->prefs[j].type=PREFTYPE_NONE;
446
534
  uid->prefs[j].value=0;
447
535
 
448
 
  uid->mdc_feature=mdc_available;
449
 
  uid->ks_modify=ks_modify;
 
536
  uid->flags.mdc=mdc_available;
 
537
  uid->flags.ks_modify=ks_modify;
450
538
 
451
539
  return uid;
452
540
}
467
555
 
468
556
    if (!s || !n) { /* create a new one */
469
557
        n = 1;
470
 
        buf = xcalloc (1,n);
 
558
        buf = xmalloc_clear (n);
471
559
    }
472
560
    else {
473
561
        buf = xmalloc (n);
511
599
 
512
600
  if (!s || !n) { /* create a new one */
513
601
    n = 1;
514
 
    buf = xcalloc (1,n);
 
602
    buf = xmalloc_clear (n);
515
603
  }
516
604
  else {
517
605
    buf = xmalloc (n);
591
679
    return 0;
592
680
}
593
681
 
594
 
 
595
682
int
596
683
keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
597
684
{
598
685
  const char *url=opaque;
599
686
 
600
 
  build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
601
 
 
602
 
  return 0;
603
 
}
604
 
 
 
687
  if(url)
 
688
    build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
 
689
  else
 
690
    delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
 
691
 
 
692
  return 0;
 
693
}
 
694
 
 
695
int
 
696
keygen_add_notations(PKT_signature *sig,void *opaque)
 
697
{
 
698
  struct notation *notation;
 
699
 
 
700
  /* We always start clean */
 
701
  delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
 
702
  delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
 
703
  sig->flags.notation=0;
 
704
 
 
705
  for(notation=opaque;notation;notation=notation->next)
 
706
    if(!notation->flags.ignore)
 
707
      {
 
708
        unsigned char *buf;
 
709
        unsigned int n1,n2;
 
710
 
 
711
        n1=strlen(notation->name);
 
712
        if(notation->altvalue)
 
713
          n2=strlen(notation->altvalue);
 
714
        else if(notation->bdat)
 
715
          n2=notation->blen;
 
716
        else
 
717
          n2=strlen(notation->value);
 
718
 
 
719
        buf = xmalloc( 8 + n1 + n2 );
 
720
 
 
721
        /* human readable or not */
 
722
        buf[0] = notation->bdat?0:0x80;
 
723
        buf[1] = buf[2] = buf[3] = 0;
 
724
        buf[4] = n1 >> 8;
 
725
        buf[5] = n1;
 
726
        buf[6] = n2 >> 8;
 
727
        buf[7] = n2;
 
728
        memcpy(buf+8, notation->name, n1 );
 
729
        if(notation->altvalue)
 
730
          memcpy(buf+8+n1, notation->altvalue, n2 );
 
731
        else if(notation->bdat)
 
732
          memcpy(buf+8+n1, notation->bdat, n2 );
 
733
        else
 
734
          memcpy(buf+8+n1, notation->value, n2 );
 
735
        build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
 
736
                          (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
 
737
                          buf, 8+n1+n2 );
 
738
        xfree(buf);
 
739
      }
 
740
 
 
741
  return 0;
 
742
}
605
743
 
606
744
int
607
745
keygen_add_revkey(PKT_signature *sig, void *opaque)
625
763
  return 0;
626
764
}
627
765
 
 
766
int
 
767
make_backsig(PKT_signature *sig,PKT_public_key *pk,
 
768
             PKT_public_key *sub_pk,PKT_secret_key *sub_sk)
 
769
{
 
770
  PKT_signature *backsig;
 
771
  int rc;
 
772
 
 
773
  cache_public_key(sub_pk);
 
774
 
 
775
  rc=make_keysig_packet(&backsig,pk,NULL,sub_pk,sub_sk,0x19,0,0,0,0,NULL,NULL);
 
776
  if(rc)
 
777
    log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
 
778
  else
 
779
    {
 
780
      /* get it into a binary packed form. */
 
781
      IOBUF backsig_out=iobuf_temp();
 
782
      PACKET backsig_pkt;
 
783
 
 
784
      init_packet(&backsig_pkt);
 
785
      backsig_pkt.pkttype=PKT_SIGNATURE;
 
786
      backsig_pkt.pkt.signature=backsig;
 
787
      rc=build_packet(backsig_out,&backsig_pkt);
 
788
      free_packet(&backsig_pkt);
 
789
      if(rc)
 
790
        log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
 
791
      else
 
792
        {
 
793
          size_t pktlen=0;
 
794
          byte *buf=iobuf_get_temp_buffer(backsig_out);
 
795
 
 
796
          /* Remove the packet header */
 
797
          if(buf[0]&0x40)
 
798
            {
 
799
              if(buf[1]<192)
 
800
                {
 
801
                  pktlen=buf[1];
 
802
                  buf+=2;
 
803
                }
 
804
              else if(buf[1]<224)
 
805
                {
 
806
                  pktlen=(buf[1]-192)*256;
 
807
                  pktlen+=buf[2]+192;
 
808
                  buf+=3;
 
809
                }
 
810
              else if(buf[1]==255)
 
811
                {
 
812
                  pktlen =buf[2] << 24;
 
813
                  pktlen|=buf[3] << 16;
 
814
                  pktlen|=buf[4] << 8;
 
815
                  pktlen|=buf[5];
 
816
                  buf+=6;
 
817
                }
 
818
              else
 
819
                BUG();
 
820
            }
 
821
          else
 
822
            {
 
823
              int mark=1;
 
824
 
 
825
              switch(buf[0]&3)
 
826
                {
 
827
                case 3:
 
828
                  BUG();
 
829
                  break;
 
830
 
 
831
                case 2:
 
832
                  pktlen =buf[mark++] << 24;
 
833
                  pktlen|=buf[mark++] << 16;
 
834
 
 
835
                case 1:
 
836
                  pktlen|=buf[mark++] << 8;
 
837
 
 
838
                case 0:
 
839
                  pktlen|=buf[mark++];
 
840
                }
 
841
 
 
842
              buf+=mark;
 
843
            }
 
844
 
 
845
          /* now make the binary blob into a subpacket */
 
846
          build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
 
847
 
 
848
          iobuf_close(backsig_out);
 
849
        }
 
850
    }
 
851
 
 
852
  return rc;
 
853
}
 
854
 
 
855
 
628
856
static int
629
857
write_direct_sig( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
630
858
                  struct revocation_key *revkey )
652
880
    rc = make_keysig_packet(&sig,pk,NULL,NULL,sk,0x1F,0,0,0,0,
653
881
                            keygen_add_revkey,revkey);
654
882
    if( rc ) {
655
 
        log_error("make_keysig_packet failed: %s\n", gpg_strerror (rc) );
 
883
        log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
656
884
        return rc;
657
885
    }
658
886
 
659
 
    pkt = xcalloc (1, sizeof *pkt );
 
887
    pkt = xmalloc_clear( sizeof *pkt );
660
888
    pkt->pkttype = PKT_SIGNATURE;
661
889
    pkt->pkt.signature = sig;
662
890
    add_kbnode( root, new_kbnode( pkt ) );
664
892
}
665
893
 
666
894
static int
667
 
write_selfsig( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
668
 
               unsigned int use )
 
895
write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
 
896
                unsigned int use )
669
897
{
670
898
    PACKET *pkt;
671
899
    PKT_signature *sig;
678
906
        log_info(_("writing self signature\n"));
679
907
 
680
908
    /* get the uid packet from the list */
681
 
    node = find_kbnode( root, PKT_USER_ID );
 
909
    node = find_kbnode( pub_root, PKT_USER_ID );
682
910
    if( !node )
683
911
        BUG(); /* no user id packet in tree */
684
912
    uid = node->pkt->pkt.user_id;
696
924
    rc = make_keysig_packet( &sig, pk, uid, NULL, sk, 0x13, 0, 0, 0, 0,
697
925
                             keygen_add_std_prefs, pk );
698
926
    if( rc ) {
699
 
        log_error("make_keysig_packet failed: %s\n", gpg_strerror (rc) );
 
927
        log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
700
928
        return rc;
701
929
    }
702
930
 
703
 
    pkt = xcalloc (1, sizeof *pkt );
 
931
    pkt = xmalloc_clear( sizeof *pkt );
704
932
    pkt->pkttype = PKT_SIGNATURE;
705
933
    pkt->pkt.signature = sig;
706
 
    add_kbnode( root, new_kbnode( pkt ) );
 
934
    add_kbnode( sec_root, new_kbnode( pkt ) );
 
935
 
 
936
    pkt = xmalloc_clear( sizeof *pkt );
 
937
    pkt->pkttype = PKT_SIGNATURE;
 
938
    pkt->pkt.signature = copy_signature(NULL,sig);
 
939
    add_kbnode( pub_root, new_kbnode( pkt ) );
707
940
    return rc;
708
941
}
709
942
 
 
943
/* sub_sk is currently unused (reserved for backsigs) */
710
944
static int
711
 
write_keybinding( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
 
945
write_keybinding( KBNODE root, KBNODE pub_root,
 
946
                  PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
712
947
                  unsigned int use )
713
948
{
714
949
    PACKET *pkt;
715
950
    PKT_signature *sig;
716
951
    int rc=0;
717
952
    KBNODE node;
718
 
    PKT_public_key *pk, *subpk;
 
953
    PKT_public_key *pri_pk, *sub_pk;
719
954
    struct opaque_data_usage_and_pk oduap;
720
955
 
721
956
    if( opt.verbose )
725
960
    node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
726
961
    if( !node )
727
962
        BUG();
728
 
    pk = node->pkt->pkt.public_key;
 
963
    pri_pk = node->pkt->pkt.public_key;
729
964
    /* we have to cache the key, so that the verification of the signature
730
965
     * creation is able to retrieve the public key */
731
 
    cache_public_key (pk);
 
966
    cache_public_key (pri_pk);
732
967
 
733
968
    /* find the last subkey */
734
 
    subpk = NULL;
 
969
    sub_pk = NULL;
735
970
    for(node=pub_root; node; node = node->next ) {
736
971
        if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
737
 
            subpk = node->pkt->pkt.public_key;
 
972
            sub_pk = node->pkt->pkt.public_key;
738
973
    }
739
 
    if( !subpk )
 
974
    if( !sub_pk )
740
975
        BUG();
741
976
 
742
977
    /* and make the signature */
743
978
    oduap.usage = use;
744
 
    oduap.pk = subpk;
745
 
    rc = make_keysig_packet( &sig, pk, NULL, subpk, sk, 0x18, 0, 0, 0, 0,
746
 
                             keygen_add_key_flags_and_expire, &oduap );
 
979
    oduap.pk = sub_pk;
 
980
    rc=make_keysig_packet(&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18, 0, 0, 0, 0,
 
981
                          keygen_add_key_flags_and_expire, &oduap );
747
982
    if( rc ) {
748
 
        log_error("make_keysig_packet failed: %s\n", gpg_strerror (rc) );
 
983
        log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
749
984
        return rc;
750
985
    }
751
986
 
752
 
    pkt = xcalloc (1, sizeof *pkt );
 
987
    /* make a backsig */
 
988
    if(use&PUBKEY_USAGE_SIG)
 
989
      {
 
990
        rc=make_backsig(sig,pri_pk,sub_pk,sub_sk);
 
991
        if(rc)
 
992
          return rc;
 
993
      }
 
994
 
 
995
    pkt = xmalloc_clear( sizeof *pkt );
753
996
    pkt->pkttype = PKT_SIGNATURE;
754
997
    pkt->pkt.signature = sig;
755
998
    add_kbnode( root, new_kbnode( pkt ) );
757
1000
}
758
1001
 
759
1002
 
 
1003
 
760
1004
static int
761
1005
key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
762
1006
               const char *topname, const char *elems)
827
1071
static void
828
1072
genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
829
1073
{
 
1074
#if 0 /* Not used anymore */
830
1075
  size_t n;
831
1076
  char *buf;
832
1077
  
849
1094
      xfree (buf);
850
1095
      gcry_sexp_release (misc_key_info);
851
1096
    }
 
1097
#endif
852
1098
}
853
1099
 
854
1100
 
855
1101
static int
856
1102
gen_elg(int algo, unsigned int nbits,
857
1103
        KBNODE pub_root, KBNODE sec_root, DEK *dek,
858
 
        STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
 
1104
        STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval,
 
1105
        int is_subkey)
859
1106
{
860
 
  int rc;
861
 
  PACKET *pkt;
862
 
  PKT_secret_key *sk;
863
 
  PKT_public_key *pk;
864
 
  gcry_sexp_t s_parms, s_key;
865
 
  gcry_sexp_t misc_key_info;
866
 
  
867
 
  assert (is_ELGAMAL(algo));
868
 
 
869
 
  if (nbits < 512)
870
 
    {
871
 
      nbits = 1024;
872
 
      log_info (_("keysize invalid; using %u bits\n"), nbits);
873
 
    }
874
 
 
875
 
  if ((nbits % 32))
876
 
    {
877
 
      nbits = ((nbits + 31) / 32) * 32;
878
 
      log_info (_("keysize rounded up to %u bits\n"), nbits);
879
 
    }
880
 
 
881
 
  rc = gcry_sexp_build ( &s_parms, NULL,
882
 
                         "(genkey(%s(nbits %d)))",
883
 
                         algo == GCRY_PK_ELG_E ? "openpgp-elg" :
884
 
                         algo == GCRY_PK_ELG     ? "elg" : "x-oops" ,
885
 
                         (int)nbits);
886
 
  if (rc)
887
 
    log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
888
 
  
889
 
  rc = gcry_pk_genkey (&s_key, s_parms);
890
 
  gcry_sexp_release (s_parms);
891
 
  if (rc)
892
 
    {
893
 
      log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
894
 
      return rc;
895
 
    }
896
 
 
897
 
  sk = xcalloc (1, sizeof *sk);
898
 
  pk = xcalloc (1, sizeof *pk);
899
 
  sk->timestamp = pk->timestamp = make_timestamp();
900
 
  sk->version = pk->version = 4;
901
 
  if (expireval)
902
 
    sk->expiredate = pk->expiredate = sk->timestamp + expireval;
903
 
  sk->pubkey_algo = pk->pubkey_algo = algo;
904
 
 
905
 
  rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
906
 
  if (rc) 
907
 
    {
908
 
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
909
 
      gcry_sexp_release (s_key);
910
 
      return rc;
911
 
    }
912
 
  rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
913
 
  if (rc)
914
 
    {
915
 
      log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
916
 
      gcry_sexp_release (s_key);
917
 
      return rc;
918
 
    }
919
 
  misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
920
 
  gcry_sexp_release (s_key);
921
 
 
922
 
  sk->is_protected = 0;
923
 
  sk->protect.algo = 0;
924
 
 
925
 
  sk->csum = checksum_mpi (sk->skey[3]);
926
 
  if (ret_sk) /* not a subkey: return an unprotected version of the sk */
927
 
    *ret_sk = copy_secret_key (NULL, sk);
928
 
 
929
 
  rc = genhelp_protect (dek, s2k, sk);
930
 
  if (rc)
931
 
    {
932
 
      free_public_key (pk);
933
 
      free_secret_key (sk);
934
 
      gcry_sexp_release (misc_key_info);
935
 
      return rc;
936
 
    }
937
 
 
938
 
  pkt = xcalloc (1,sizeof *pkt);
939
 
  pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
940
 
  pkt->pkt.public_key = pk;
941
 
  add_kbnode(pub_root, new_kbnode( pkt ));
942
 
  
943
 
  /* don't know whether it makes sense to have the factors, so for now
944
 
   * we store them in the secret keyring (but they are not secret) */
945
 
  pkt = xcalloc (1,sizeof *pkt);
946
 
  pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
947
 
  pkt->pkt.secret_key = sk;
948
 
  add_kbnode(sec_root, new_kbnode( pkt ));
949
 
  
950
 
  genhelp_factors (misc_key_info, sec_root);
951
 
  
952
 
  return 0;
 
1107
    int rc;
 
1108
    PACKET *pkt;
 
1109
    PKT_secret_key *sk;
 
1110
    PKT_public_key *pk;
 
1111
    gcry_sexp_t s_parms, s_key;
 
1112
    gcry_sexp_t misc_key_info;
 
1113
 
 
1114
    assert( is_ELGAMAL(algo) );
 
1115
 
 
1116
    if( nbits < 512 ) {
 
1117
        nbits = 1024;
 
1118
        log_info(_("keysize invalid; using %u bits\n"), nbits );
 
1119
    }
 
1120
 
 
1121
    if( (nbits % 32) ) {
 
1122
        nbits = ((nbits + 31) / 32) * 32;
 
1123
        log_info(_("keysize rounded up to %u bits\n"), nbits );
 
1124
    }
 
1125
 
 
1126
 
 
1127
    rc = gcry_sexp_build ( &s_parms, NULL,
 
1128
                           "(genkey(%s(nbits %d)))",
 
1129
                           algo == GCRY_PK_ELG_E ? "openpgp-elg" :
 
1130
                           algo == GCRY_PK_ELG   ? "elg" : "x-oops" ,
 
1131
                           (int)nbits);
 
1132
    if (rc)
 
1133
      log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
 
1134
  
 
1135
    rc = gcry_pk_genkey (&s_key, s_parms);
 
1136
    gcry_sexp_release (s_parms);
 
1137
    if (rc)
 
1138
      {
 
1139
        log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
 
1140
        return rc;
 
1141
      }
 
1142
 
 
1143
    sk = xmalloc_clear( sizeof *sk );
 
1144
    pk = xmalloc_clear( sizeof *pk );
 
1145
    sk->timestamp = pk->timestamp = make_timestamp();
 
1146
    sk->version = pk->version = 4;
 
1147
    if( expireval ) {
 
1148
        sk->expiredate = pk->expiredate = sk->timestamp + expireval;
 
1149
    }
 
1150
    sk->pubkey_algo = pk->pubkey_algo = algo;
 
1151
/*                     pk->pkey[0] = mpi_copy( skey[0] ); */
 
1152
/*                     pk->pkey[1] = mpi_copy( skey[1] ); */
 
1153
/*                     pk->pkey[2] = mpi_copy( skey[2] ); */
 
1154
/*     sk->skey[0] = skey[0]; */
 
1155
/*     sk->skey[1] = skey[1]; */
 
1156
/*     sk->skey[2] = skey[2]; */
 
1157
/*     sk->skey[3] = skey[3]; */
 
1158
 
 
1159
    rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
 
1160
    if (rc) 
 
1161
      {
 
1162
        log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
 
1163
        gcry_sexp_release (s_key);
 
1164
        free_secret_key (sk);
 
1165
        free_public_key (pk);
 
1166
        return rc;
 
1167
      }
 
1168
    rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
 
1169
    if (rc)
 
1170
      {
 
1171
        log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
 
1172
        gcry_sexp_release (s_key);
 
1173
        free_secret_key (sk);
 
1174
        free_public_key (pk);
 
1175
        return rc;
 
1176
      }
 
1177
    misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
 
1178
    gcry_sexp_release (s_key);
 
1179
  
 
1180
    sk->is_protected = 0;
 
1181
    sk->protect.algo = 0;
 
1182
 
 
1183
    sk->csum = checksum_mpi( sk->skey[3] );
 
1184
    if( ret_sk ) /* return an unprotected version of the sk */
 
1185
        *ret_sk = copy_secret_key( NULL, sk );
 
1186
 
 
1187
    rc = genhelp_protect (dek, s2k, sk);
 
1188
    if (rc)
 
1189
      {
 
1190
        free_public_key (pk);
 
1191
        free_secret_key (sk);
 
1192
        gcry_sexp_release (misc_key_info);
 
1193
        return rc;
 
1194
      }
 
1195
 
 
1196
    pkt = xmalloc_clear (sizeof *pkt);
 
1197
    pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
 
1198
    pkt->pkt.public_key = pk;
 
1199
    add_kbnode(pub_root, new_kbnode( pkt ));
 
1200
 
 
1201
    /* Don't know whether it makes sense to have the factors, so for now
 
1202
     * we store them in the secret keyring (but they are not secret). */
 
1203
    pkt = xmalloc_clear(sizeof *pkt);
 
1204
    pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
 
1205
    pkt->pkt.secret_key = sk;
 
1206
    add_kbnode(sec_root, new_kbnode( pkt ));
 
1207
 
 
1208
    genhelp_factors (misc_key_info, sec_root);
 
1209
 
 
1210
    return 0;
953
1211
}
954
1212
 
955
1213
 
958
1216
 */
959
1217
static int
960
1218
gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
961
 
         STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
 
1219
        STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval, int is_subkey)
962
1220
{
963
 
  int rc;
964
 
  PACKET *pkt;
965
 
  PKT_secret_key *sk;
966
 
  PKT_public_key *pk;
967
 
  gcry_sexp_t s_parms, s_key;
968
 
  gcry_sexp_t misc_key_info;
969
 
 
970
 
  if (nbits > 1024 || nbits < 512)
971
 
    {
972
 
      nbits = 1024;
973
 
      log_info(_("keysize invalid; using %u bits\n"), nbits);
974
 
    }
975
 
 
976
 
  if ((nbits % 64))
977
 
    {
978
 
      nbits = ((nbits + 63) / 64) * 64;
979
 
      log_info (_("keysize rounded up to %u bits\n"), nbits);
980
 
    }
981
 
 
982
 
  rc = gcry_sexp_build (&s_parms, NULL,
983
 
                        "(genkey(dsa(nbits %d)))",
984
 
                        (int)nbits);
985
 
  if (rc)
986
 
    log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
987
 
  
988
 
  rc = gcry_pk_genkey (&s_key, s_parms);
989
 
  gcry_sexp_release (s_parms);
990
 
  if (rc)
991
 
    {
992
 
      log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
993
 
      return rc;
994
 
    }
995
 
 
996
 
  sk = xcalloc (1, sizeof *sk );
997
 
  pk = xcalloc (1, sizeof *pk );
998
 
  sk->timestamp = pk->timestamp = make_timestamp();
999
 
  sk->version = pk->version = 4;
1000
 
  if (expireval) 
1001
 
    sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1002
 
  sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1003
 
 
1004
 
  rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1005
 
  if (rc) 
1006
 
    {
1007
 
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1008
 
      gcry_sexp_release (s_key);
1009
 
      return rc;
1010
 
    }
1011
 
  rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1012
 
  if (rc) 
1013
 
    {
1014
 
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1015
 
      gcry_sexp_release (s_key);
1016
 
      return rc;
1017
 
    }
1018
 
  misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1019
 
  gcry_sexp_release (s_key);
1020
 
 
1021
 
  sk->is_protected = 0;
1022
 
  sk->protect.algo = 0;
1023
 
 
1024
 
  sk->csum = checksum_mpi ( sk->skey[4] );
1025
 
  if (ret_sk) /* not a subkey: return an unprotected version of the sk */
1026
 
    *ret_sk = copy_secret_key( NULL, sk );
1027
 
 
1028
 
  rc = genhelp_protect (dek, s2k, sk);
1029
 
  if (rc)
1030
 
    {
1031
 
      free_public_key (pk);
1032
 
      free_secret_key (sk);
1033
 
      gcry_sexp_release (misc_key_info);
1034
 
      return rc;
1035
 
    }
1036
 
 
1037
 
  pkt = xcalloc (1,sizeof *pkt);
1038
 
  pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
1039
 
  pkt->pkt.public_key = pk;
1040
 
  add_kbnode(pub_root, new_kbnode( pkt ));
1041
 
 
1042
 
  pkt = xcalloc (1,sizeof *pkt);
1043
 
  pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
1044
 
  pkt->pkt.secret_key = sk;
1045
 
  add_kbnode(sec_root, new_kbnode( pkt ));
1046
 
 
1047
 
  genhelp_factors (misc_key_info, sec_root);
1048
 
 
1049
 
  return 0;
 
1221
    int rc;
 
1222
    PACKET *pkt;
 
1223
    PKT_secret_key *sk;
 
1224
    PKT_public_key *pk;
 
1225
    gcry_sexp_t s_parms, s_key;
 
1226
    gcry_sexp_t misc_key_info;
 
1227
 
 
1228
    if( nbits > 1024 || nbits < 512 ) {
 
1229
        nbits = 1024;
 
1230
        log_info(_("keysize invalid; using %u bits\n"), nbits );
 
1231
    }
 
1232
 
 
1233
    if( (nbits % 64) ) {
 
1234
        nbits = ((nbits + 63) / 64) * 64;
 
1235
        log_info(_("keysize rounded up to %u bits\n"), nbits );
 
1236
    }
 
1237
 
 
1238
    rc = gcry_sexp_build (&s_parms, NULL,
 
1239
                          "(genkey(dsa(nbits %d)))",
 
1240
                          (int)nbits);
 
1241
    if (rc)
 
1242
      log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
 
1243
  
 
1244
    rc = gcry_pk_genkey (&s_key, s_parms);
 
1245
    gcry_sexp_release (s_parms);
 
1246
    if (rc)
 
1247
      {
 
1248
        log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
 
1249
        return rc;
 
1250
      }
 
1251
 
 
1252
    sk = xmalloc_clear( sizeof *sk );
 
1253
    pk = xmalloc_clear( sizeof *pk );
 
1254
    sk->timestamp = pk->timestamp = make_timestamp();
 
1255
    sk->version = pk->version = 4;
 
1256
    if( expireval ) {
 
1257
        sk->expiredate = pk->expiredate = sk->timestamp + expireval;
 
1258
    }
 
1259
    sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
 
1260
 
 
1261
    rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
 
1262
    if (rc) 
 
1263
      {
 
1264
        log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
 
1265
        gcry_sexp_release (s_key);
 
1266
        free_public_key(pk);
 
1267
        free_secret_key(sk);
 
1268
        return rc;
 
1269
      }
 
1270
    rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
 
1271
    if (rc) 
 
1272
      {
 
1273
        log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
 
1274
        gcry_sexp_release (s_key);
 
1275
        free_public_key(pk);
 
1276
        free_secret_key(sk);
 
1277
        return rc;
 
1278
      }
 
1279
    misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
 
1280
    gcry_sexp_release (s_key);
 
1281
  
 
1282
    sk->is_protected = 0;
 
1283
    sk->protect.algo = 0;
 
1284
 
 
1285
    sk->csum = checksum_mpi ( sk->skey[4] );
 
1286
    if( ret_sk ) /* return an unprotected version of the sk */
 
1287
        *ret_sk = copy_secret_key( NULL, sk );
 
1288
 
 
1289
    rc = genhelp_protect (dek, s2k, sk);
 
1290
    if (rc)
 
1291
      {
 
1292
        free_public_key (pk);
 
1293
        free_secret_key (sk);
 
1294
        gcry_sexp_release (misc_key_info);
 
1295
        return rc;
 
1296
      }
 
1297
 
 
1298
    pkt = xmalloc_clear(sizeof *pkt);
 
1299
    pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
 
1300
    pkt->pkt.public_key = pk;
 
1301
    add_kbnode(pub_root, new_kbnode( pkt ));
 
1302
 
 
1303
    /* Don't know whether it makes sense to have the factors, so for now
 
1304
     * we store them in the secret keyring (but they are not secret)
 
1305
     * p = 2 * q * f1 * f2 * ... * fn
 
1306
     * We store only f1 to f_n-1;  fn can be calculated because p and q
 
1307
     * are known.
 
1308
     */
 
1309
    pkt = xmalloc_clear(sizeof *pkt);
 
1310
    pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
 
1311
    pkt->pkt.secret_key = sk;
 
1312
    add_kbnode(sec_root, new_kbnode( pkt ));
 
1313
 
 
1314
    genhelp_factors (misc_key_info, sec_root);
 
1315
 
 
1316
    return 0;
1050
1317
}
1051
1318
 
1052
1319
 
1055
1322
 */
1056
1323
static int
1057
1324
gen_rsa(int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1058
 
        STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
 
1325
        STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval, int is_subkey)
1059
1326
{
1060
 
  int rc;
1061
 
  PACKET *pkt;
1062
 
  PKT_secret_key *sk;
1063
 
  PKT_public_key *pk;
1064
 
  gcry_sexp_t s_parms, s_key;
1065
 
 
1066
 
  assert (is_RSA(algo));
1067
 
 
1068
 
  if (nbits < 1024)
1069
 
    {
1070
 
      nbits = 1024;
1071
 
      log_info(_("keysize invalid; using %u bits\n"), nbits);
1072
 
    }
1073
 
 
1074
 
  if ((nbits % 32))
1075
 
    {
1076
 
      nbits = ((nbits + 31) / 32) * 32;
1077
 
      log_info (_("keysize rounded up to %u bits\n"), nbits);
1078
 
    }
1079
 
 
1080
 
  rc = gcry_sexp_build (&s_parms, NULL,
1081
 
                        "(genkey(rsa(nbits %d)))",
1082
 
                        (int)nbits);
1083
 
  if (rc)
1084
 
    log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
 
1327
    int rc;
 
1328
    PACKET *pkt;
 
1329
    PKT_secret_key *sk;
 
1330
    PKT_public_key *pk;
 
1331
    gcry_sexp_t s_parms, s_key;
 
1332
 
 
1333
    assert( is_RSA(algo) );
 
1334
 
 
1335
    if( nbits < 1024 ) {
 
1336
        nbits = 1024;
 
1337
        log_info(_("keysize invalid; using %u bits\n"), nbits );
 
1338
    }
 
1339
 
 
1340
    if( (nbits % 32) ) {
 
1341
        nbits = ((nbits + 31) / 32) * 32;
 
1342
        log_info(_("keysize rounded up to %u bits\n"), nbits );
 
1343
    }
 
1344
 
 
1345
    rc = gcry_sexp_build (&s_parms, NULL,
 
1346
                          "(genkey(rsa(nbits %d)))",
 
1347
                          (int)nbits);
 
1348
    if (rc)
 
1349
      log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1085
1350
  
1086
 
  rc = gcry_pk_genkey (&s_key, s_parms);
1087
 
  gcry_sexp_release (s_parms);
1088
 
  if (rc)
1089
 
    {
1090
 
      log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1091
 
      return rc;
1092
 
    }
1093
 
 
1094
 
  sk = xcalloc (1, sizeof *sk );
1095
 
  pk = xcalloc (1, sizeof *pk );
1096
 
  sk->timestamp = pk->timestamp = make_timestamp();
1097
 
  sk->version = pk->version = 4;
1098
 
  if (expireval) 
1099
 
    sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1100
 
  sk->pubkey_algo = pk->pubkey_algo = algo;
1101
 
 
1102
 
  rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1103
 
  if (rc) 
1104
 
    {
1105
 
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1106
 
      gcry_sexp_release (s_key);
1107
 
      return rc;
1108
 
    }
1109
 
  rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1110
 
  if (rc) 
1111
 
    {
1112
 
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1113
 
      gcry_sexp_release (s_key);
1114
 
      return rc;
1115
 
    }
1116
 
  gcry_sexp_release (s_key);
1117
 
 
1118
 
  sk->is_protected = 0;
1119
 
  sk->protect.algo = 0;
1120
 
 
1121
 
  sk->csum  = checksum_mpi (sk->skey[2] );
1122
 
  sk->csum += checksum_mpi (sk->skey[3] );
1123
 
  sk->csum += checksum_mpi (sk->skey[4] );
1124
 
  sk->csum += checksum_mpi (sk->skey[5] );
1125
 
  if (ret_sk) /* not a subkey: return an unprotected version of the sk */
1126
 
    *ret_sk = copy_secret_key (NULL, sk);
1127
 
 
1128
 
  rc = genhelp_protect (dek, s2k, sk);
1129
 
  if (rc)
1130
 
    {
1131
 
      free_public_key (pk);
1132
 
      free_secret_key (sk);
1133
 
      return rc;
1134
 
    }
1135
 
 
1136
 
  pkt = xcalloc (1,sizeof *pkt);
1137
 
  pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
1138
 
  pkt->pkt.public_key = pk;
1139
 
  add_kbnode (pub_root, new_kbnode( pkt ));
1140
 
 
1141
 
  pkt = xcalloc (1,sizeof *pkt);
1142
 
  pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
1143
 
  pkt->pkt.secret_key = sk;
1144
 
  add_kbnode(sec_root, new_kbnode( pkt ));
1145
 
 
1146
 
  return 0;
 
1351
    rc = gcry_pk_genkey (&s_key, s_parms);
 
1352
    gcry_sexp_release (s_parms);
 
1353
    if (rc)
 
1354
      {
 
1355
        log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
 
1356
        return rc;
 
1357
      }
 
1358
 
 
1359
    sk = xmalloc_clear( sizeof *sk );
 
1360
    pk = xmalloc_clear( sizeof *pk );
 
1361
    sk->timestamp = pk->timestamp = make_timestamp();
 
1362
    sk->version = pk->version = 4;
 
1363
    if( expireval ) {
 
1364
        sk->expiredate = pk->expiredate = sk->timestamp + expireval;
 
1365
    }
 
1366
    sk->pubkey_algo = pk->pubkey_algo = algo;
 
1367
 
 
1368
    rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
 
1369
    if (rc) 
 
1370
      {
 
1371
        log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
 
1372
        gcry_sexp_release (s_key);
 
1373
        free_public_key(pk);
 
1374
        free_secret_key(sk);
 
1375
        return rc;
 
1376
      }
 
1377
    rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
 
1378
    if (rc) 
 
1379
      {
 
1380
        log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
 
1381
        gcry_sexp_release (s_key);
 
1382
        free_public_key(pk);
 
1383
        free_secret_key(sk);
 
1384
        return rc;
 
1385
      }
 
1386
    gcry_sexp_release (s_key);
 
1387
 
 
1388
    sk->is_protected = 0;
 
1389
    sk->protect.algo = 0;
 
1390
 
 
1391
    sk->csum  = checksum_mpi (sk->skey[2] );
 
1392
    sk->csum += checksum_mpi (sk->skey[3] );
 
1393
    sk->csum += checksum_mpi (sk->skey[4] );
 
1394
    sk->csum += checksum_mpi (sk->skey[5] );
 
1395
    if( ret_sk ) /* return an unprotected version of the sk */
 
1396
        *ret_sk = copy_secret_key( NULL, sk );
 
1397
 
 
1398
    rc = genhelp_protect (dek, s2k, sk);
 
1399
    if (rc)
 
1400
      {
 
1401
        free_public_key (pk);
 
1402
        free_secret_key (sk);
 
1403
        return rc;
 
1404
      }
 
1405
 
 
1406
    pkt = xmalloc_clear(sizeof *pkt);
 
1407
    pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
 
1408
    pkt->pkt.public_key = pk;
 
1409
    add_kbnode(pub_root, new_kbnode( pkt ));
 
1410
 
 
1411
    pkt = xmalloc_clear(sizeof *pkt);
 
1412
    pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
 
1413
    pkt->pkt.secret_key = sk;
 
1414
    add_kbnode(sec_root, new_kbnode( pkt ));
 
1415
 
 
1416
    return 0;
1147
1417
}
1148
1418
 
1149
1419
 
1175
1445
}
1176
1446
 
1177
1447
 
 
1448
static void
 
1449
print_key_flags(int flags)
 
1450
{
 
1451
  if(flags&PUBKEY_USAGE_SIG)
 
1452
    tty_printf("%s ",_("Sign"));
 
1453
 
 
1454
  if(flags&PUBKEY_USAGE_CERT)
 
1455
    tty_printf("%s ",_("Certify"));
 
1456
 
 
1457
  if(flags&PUBKEY_USAGE_ENC)
 
1458
    tty_printf("%s ",_("Encrypt"));
 
1459
 
 
1460
  if(flags&PUBKEY_USAGE_AUTH)
 
1461
    tty_printf("%s ",_("Authenticate"));
 
1462
}
 
1463
 
 
1464
 
 
1465
/* Returns the key flags */
 
1466
static unsigned int
 
1467
ask_key_flags(int algo,int subkey)
 
1468
{
 
1469
  const char *togglers=_("SsEeAaQq");
 
1470
  char *answer=NULL;
 
1471
  unsigned int current=0;
 
1472
  unsigned int possible=openpgp_pk_algo_usage(algo);
 
1473
 
 
1474
  if(strlen(togglers)!=8)
 
1475
    BUG();
 
1476
 
 
1477
  /* Only primary keys may certify. */
 
1478
  if(subkey)
 
1479
    possible&=~PUBKEY_USAGE_CERT;
 
1480
 
 
1481
  /* Preload the current set with the possible set, minus
 
1482
     authentication, since nobody really uses auth yet. */
 
1483
  current=possible&~PUBKEY_USAGE_AUTH;
 
1484
 
 
1485
  for(;;)
 
1486
    {
 
1487
      tty_printf("\n");
 
1488
      tty_printf(_("Possible actions for a %s key: "),
 
1489
                 gcry_pk_algo_name (algo));
 
1490
      print_key_flags(possible);
 
1491
      tty_printf("\n");
 
1492
      tty_printf(_("Current allowed actions: "));
 
1493
      print_key_flags(current);
 
1494
      tty_printf("\n\n");
 
1495
 
 
1496
      if(possible&PUBKEY_USAGE_SIG)
 
1497
        tty_printf(_("   (%c) Toggle the sign capability\n"),
 
1498
                   togglers[0]);
 
1499
      if(possible&PUBKEY_USAGE_ENC)
 
1500
        tty_printf(_("   (%c) Toggle the encrypt capability\n"),
 
1501
                   togglers[2]);
 
1502
      if(possible&PUBKEY_USAGE_AUTH)
 
1503
        tty_printf(_("   (%c) Toggle the authenticate capability\n"),
 
1504
                   togglers[4]);
 
1505
 
 
1506
      tty_printf(_("   (%c) Finished\n"),togglers[6]);
 
1507
      tty_printf("\n");
 
1508
 
 
1509
      xfree(answer);
 
1510
      answer = cpr_get("keygen.flags",_("Your selection? "));
 
1511
      cpr_kill_prompt();
 
1512
 
 
1513
      if(strlen(answer)>1)
 
1514
        tty_printf(_("Invalid selection.\n"));
 
1515
      else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
 
1516
        break;
 
1517
      else if((*answer==togglers[0] || *answer==togglers[1])
 
1518
              && possible&PUBKEY_USAGE_SIG)
 
1519
        {
 
1520
          if(current&PUBKEY_USAGE_SIG)
 
1521
            current&=~PUBKEY_USAGE_SIG;
 
1522
          else
 
1523
            current|=PUBKEY_USAGE_SIG;
 
1524
        }
 
1525
      else if((*answer==togglers[2] || *answer==togglers[3])
 
1526
              && possible&PUBKEY_USAGE_ENC)
 
1527
        {
 
1528
          if(current&PUBKEY_USAGE_ENC)
 
1529
            current&=~PUBKEY_USAGE_ENC;
 
1530
          else
 
1531
            current|=PUBKEY_USAGE_ENC;
 
1532
        }
 
1533
      else if((*answer==togglers[4] || *answer==togglers[5])
 
1534
              && possible&PUBKEY_USAGE_AUTH)
 
1535
        {
 
1536
          if(current&PUBKEY_USAGE_AUTH)
 
1537
            current&=~PUBKEY_USAGE_AUTH;
 
1538
          else
 
1539
            current|=PUBKEY_USAGE_AUTH;
 
1540
        }
 
1541
      else
 
1542
        tty_printf(_("Invalid selection.\n"));
 
1543
    }
 
1544
 
 
1545
  xfree(answer);
 
1546
 
 
1547
  return current;
 
1548
}
 
1549
 
 
1550
 
1178
1551
/****************
1179
 
 * Returns: 0 to create both a DSA and a ElGamal key.
 
1552
 * Returns: 0 to create both a DSA and a Elgamal key.
1180
1553
 *          and only if key flags are to be written the desired usage.
1181
1554
 */
1182
1555
static int
1188
1561
    *r_usage = 0;
1189
1562
    tty_printf(_("Please select what kind of key you want:\n"));
1190
1563
    if( !addmode )
1191
 
        tty_printf(_("   (%d) DSA and ElGamal (default)\n"), 1 );
 
1564
        tty_printf(_("   (%d) DSA and Elgamal (default)\n"), 1 );
1192
1565
    tty_printf(    _("   (%d) DSA (sign only)\n"), 2 );
 
1566
    if (opt.expert)
 
1567
      tty_printf(  _("   (%d) DSA (set your own capabilities)\n"), 3 );
1193
1568
    if( addmode )
1194
 
        tty_printf(    _("   (%d) ElGamal (encrypt only)\n"), 3 );
1195
 
    if (opt.expert)
1196
 
        tty_printf(    _("   (%d) ElGamal (sign and encrypt)\n"), 4 );
 
1569
        tty_printf(_("   (%d) Elgamal (encrypt only)\n"), 4 );
1197
1570
    tty_printf(    _("   (%d) RSA (sign only)\n"), 5 );
1198
1571
    if (addmode)
1199
 
        tty_printf(    _("   (%d) RSA (encrypt only)\n"), 6 );
 
1572
        tty_printf(_("   (%d) RSA (encrypt only)\n"), 6 );
1200
1573
    if (opt.expert)
1201
 
      tty_printf(    _("   (%d) RSA (sign and encrypt)\n"), 7 );
 
1574
      tty_printf(  _("   (%d) RSA (set your own capabilities)\n"), 7 );
1202
1575
 
1203
1576
    for(;;) {
1204
1577
        answer = cpr_get("keygen.algo",_("Your selection? "));
1205
1578
        cpr_kill_prompt();
1206
1579
        algo = *answer? atoi(answer): 1;
1207
 
        xfree (answer);
 
1580
        xfree(answer);
1208
1581
        if( algo == 1 && !addmode ) {
1209
1582
            algo = 0;   /* create both keys */
1210
1583
            break;
1211
1584
        }
1212
1585
        else if( algo == 7 && opt.expert ) {
1213
1586
            algo = PUBKEY_ALGO_RSA;
1214
 
            *r_usage = PUBKEY_USAGE_ENC | PUBKEY_USAGE_SIG;
 
1587
            *r_usage=ask_key_flags(algo,addmode);
1215
1588
            break;
1216
1589
        }
1217
1590
        else if( algo == 6 && addmode ) {
1224
1597
            *r_usage = PUBKEY_USAGE_SIG;
1225
1598
            break;
1226
1599
        }
1227
 
        else if( algo == 4 && opt.expert)
1228
 
          {
1229
 
            tty_printf(_(
1230
 
"The use of this algorithm is only supported by GnuPG.  You will not be\n"
1231
 
"able to use this key to communicate with PGP users.  This algorithm is also\n"
1232
 
"very slow, and may not be as secure as the other choices.\n"));
1233
 
 
1234
 
            if( cpr_get_answer_is_yes("keygen.algo.elg_se",
1235
 
                                      _("Create anyway? ")))
1236
 
              {
1237
 
                algo = PUBKEY_ALGO_ELGAMAL;
1238
 
                *r_usage = PUBKEY_USAGE_ENC | PUBKEY_USAGE_SIG;
1239
 
                break;
1240
 
              }
1241
 
        }
1242
 
        else if( algo == 3 && addmode ) {
 
1600
        else if( algo == 4 && addmode ) {
1243
1601
            algo = PUBKEY_ALGO_ELGAMAL_E;
1244
1602
            *r_usage = PUBKEY_USAGE_ENC;
1245
1603
            break;
1246
1604
        }
 
1605
        else if( algo == 3 && opt.expert ) {
 
1606
            algo = PUBKEY_ALGO_DSA;
 
1607
            *r_usage=ask_key_flags(algo,addmode);
 
1608
            break;
 
1609
        }
1247
1610
        else if( algo == 2 ) {
1248
1611
            algo = PUBKEY_ALGO_DSA;
1249
1612
            *r_usage = PUBKEY_USAGE_SIG;
1252
1615
        else
1253
1616
            tty_printf(_("Invalid selection.\n"));
1254
1617
    }
 
1618
 
1255
1619
    return algo;
1256
1620
}
1257
1621
 
1259
1623
static unsigned
1260
1624
ask_keysize( int algo )
1261
1625
{
1262
 
    char *answer;
1263
 
    unsigned nbits;
1264
 
 
1265
 
    if (algo != PUBKEY_ALGO_DSA && algo != PUBKEY_ALGO_RSA) {
1266
 
        tty_printf (_("About to generate a new %s keypair.\n"
1267
 
                      "              minimum keysize is  768 bits\n"
1268
 
                      "              default keysize is 1024 bits\n"
1269
 
                      "    highest suggested keysize is 2048 bits\n"),
1270
 
                    gcry_pk_algo_name (algo) );
1271
 
    }
1272
 
 
1273
 
    for(;;) {
1274
 
        answer = cpr_get("keygen.size",
1275
 
                          _("What keysize do you want? (1024) "));
1276
 
        cpr_kill_prompt();
1277
 
        nbits = *answer? atoi(answer): 1024;
1278
 
        xfree (answer);
1279
 
        if( algo == PUBKEY_ALGO_DSA && (nbits < 512 || nbits > 1024) )
1280
 
            tty_printf(_("DSA only allows keysizes from 512 to 1024\n"));
1281
 
        else if( algo == PUBKEY_ALGO_RSA && nbits < 1024 )
1282
 
            tty_printf(_("keysize too small;"
1283
 
                         " 1024 is smallest value allowed for RSA.\n"));
1284
 
        else if( nbits < 768 )
1285
 
            tty_printf(_("keysize too small;"
1286
 
                         " 768 is smallest value allowed.\n"));
1287
 
        else if( nbits > 4096 ) {
1288
 
            /* It is ridiculous and an annoyance to use larger key sizes!
1289
 
             * GnuPG can handle much larger sizes; but it takes an eternity
1290
 
             * to create such a key (but less than the time the Sirius
1291
 
             * Computer Corporation needs to process one of the usual
1292
 
             * complaints) and {de,en}cryption although needs some time.
1293
 
             * So, before you complain about this limitation, I suggest that
1294
 
             * you start a discussion with Marvin about this theme and then
1295
 
             * do whatever you want. */
1296
 
            tty_printf(_("keysize too large; %d is largest value allowed.\n"),
1297
 
                                                                         4096);
1298
 
        }
1299
 
        else if( nbits > 2048 && !cpr_enabled() ) {
1300
 
            tty_printf(
1301
 
                _("Keysizes larger than 2048 are not suggested because\n"
1302
 
                  "computations take REALLY long!\n"));
1303
 
            if( cpr_get_answer_is_yes("keygen.size.huge.okay",_(
1304
 
                        "Are you sure that you want this keysize? ")) ) {
1305
 
                tty_printf(_("Okay, but keep in mind that your monitor "
1306
 
                             "and keyboard radiation is also very vulnerable "
1307
 
                             "to attacks!\n"));
1308
 
                break;
1309
 
            }
1310
 
        }
1311
 
        else
1312
 
            break;
1313
 
    }
1314
 
    tty_printf(_("Requested keysize is %u bits\n"), nbits );
1315
 
    if( algo == PUBKEY_ALGO_DSA && (nbits % 64) ) {
1316
 
        nbits = ((nbits + 63) / 64) * 64;
1317
 
        tty_printf(_("rounded up to %u bits\n"), nbits );
1318
 
    }
1319
 
    else if( (nbits % 32) ) {
1320
 
        nbits = ((nbits + 31) / 32) * 32;
1321
 
        tty_printf(_("rounded up to %u bits\n"), nbits );
1322
 
    }
1323
 
    return nbits;
 
1626
  unsigned int nbits, min, def=2048, max=4096;
 
1627
 
 
1628
  if(opt.expert)
 
1629
    min=512;
 
1630
  else
 
1631
    min=1024;
 
1632
 
 
1633
  switch(algo)
 
1634
    {
 
1635
    case PUBKEY_ALGO_DSA:
 
1636
      if(opt.expert)
 
1637
        {
 
1638
          def=1024;
 
1639
          max=1024;
 
1640
        }
 
1641
      else
 
1642
        {
 
1643
          tty_printf(_("DSA keypair will have %u bits.\n"),1024);
 
1644
          return 1024;
 
1645
        }
 
1646
      break;
 
1647
 
 
1648
    case PUBKEY_ALGO_RSA:
 
1649
      min=1024;
 
1650
      break;
 
1651
    }
 
1652
 
 
1653
  tty_printf(_("%s keys may be between %u and %u bits long.\n"),
 
1654
             gcry_pk_algo_name (algo), min, max);
 
1655
 
 
1656
  for(;;)
 
1657
    {
 
1658
      char *prompt,*answer;
 
1659
 
 
1660
#define PROMPTSTRING _("What keysize do you want? (%u) ")
 
1661
 
 
1662
      prompt=xmalloc(strlen(PROMPTSTRING)+20);
 
1663
      sprintf(prompt,PROMPTSTRING,def);
 
1664
 
 
1665
#undef PROMPTSTRING
 
1666
 
 
1667
      answer = cpr_get("keygen.size",prompt);
 
1668
      cpr_kill_prompt();
 
1669
      nbits = *answer? atoi(answer): def;
 
1670
      xfree(prompt);
 
1671
      xfree(answer);
 
1672
      
 
1673
      if(nbits<min || nbits>max)
 
1674
        tty_printf(_("%s keysizes must be in the range %u-%u\n"),
 
1675
                   gcry_pk_algo_name (algo), min, max);
 
1676
      else
 
1677
        break;
 
1678
    }
 
1679
 
 
1680
  tty_printf(_("Requested keysize is %u bits\n"), nbits );
 
1681
 
 
1682
  if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
 
1683
    {
 
1684
      nbits = ((nbits + 63) / 64) * 64;
 
1685
      tty_printf(_("rounded up to %u bits\n"), nbits );
 
1686
    }
 
1687
  else if( (nbits % 32) )
 
1688
    {
 
1689
      nbits = ((nbits + 31) / 32) * 32;
 
1690
      tty_printf(_("rounded up to %u bits\n"), nbits );
 
1691
    }
 
1692
 
 
1693
  return nbits;
1324
1694
}
1325
1695
 
1326
1696
 
1327
1697
/****************
1328
 
 * Parse an expire string and return it's value in days.
1329
 
 * Returns -1 on error.
 
1698
 * Parse an expire string and return its value in seconds.
 
1699
 * Returns (u32)-1 on error.
 
1700
 * This isn't perfect since scan_isodatestr returns unix time, and
 
1701
 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
 
1702
 * Because of this, we only permit setting expirations up to 2106, but
 
1703
 * OpenPGP could theoretically allow up to 2242.  I think we'll all
 
1704
 * just cope for the next few years until we get a 64-bit time_t or
 
1705
 * similar.
1330
1706
 */
1331
 
static int
 
1707
u32
1332
1708
parse_expire_string( const char *string )
1333
1709
{
1334
1710
    int mult;
1335
 
    u32 abs_date=0;
1336
 
    u32 curtime = make_timestamp();
1337
 
    int valid_days;
 
1711
    u32 seconds,abs_date=0,curtime = make_timestamp();
1338
1712
 
1339
1713
    if( !*string )
1340
 
        valid_days = 0;
1341
 
    else if( (abs_date = scan_isodatestr(string)) && abs_date > curtime ) {
1342
 
        /* This calculation is not perfectly okay because we
1343
 
         * are later going to simply multiply by 86400 and don't
1344
 
         * correct for leapseconds.  A solution would be to change
1345
 
         * the whole implemenation to work with dates and not intervals
1346
 
         * which are required for v3 keys.
1347
 
         */
1348
 
        valid_days = abs_date/86400-curtime/86400+1;
1349
 
    }
1350
 
    else if( (mult=check_valid_days(string)) ) {
1351
 
        valid_days = atoi(string) * mult;
1352
 
        if( valid_days < 0 || valid_days > 39447 )
1353
 
            valid_days = 0;
1354
 
    }
1355
 
    else {
1356
 
        valid_days = -1;
1357
 
    }
1358
 
    return valid_days;
 
1714
      seconds = 0;
 
1715
    else if ( !strncmp (string, "seconds=", 8) )
 
1716
      seconds = atoi (string+8);
 
1717
    else if( (abs_date = scan_isodatestr(string)) && abs_date > curtime )
 
1718
      seconds = abs_date - curtime;
 
1719
    else if( (mult=check_valid_days(string)) )
 
1720
      seconds = atoi(string) * 86400L * mult;
 
1721
    else
 
1722
      seconds=(u32)-1;
 
1723
 
 
1724
    return seconds;
1359
1725
}
1360
1726
 
1361
1727
/* object == 0 for a key, and 1 for a sig */
1362
1728
u32
1363
 
ask_expire_interval(int object)
 
1729
ask_expire_interval(int object,const char *def_expire)
1364
1730
{
 
1731
    u32 interval;
1365
1732
    char *answer;
1366
 
    int valid_days=0;
1367
 
    u32 interval = 0;
1368
1733
 
1369
1734
    switch(object)
1370
1735
      {
1371
1736
      case 0:
 
1737
        if(def_expire)
 
1738
          BUG();
1372
1739
        tty_printf(_("Please specify how long the key should be valid.\n"
1373
1740
                     "         0 = key does not expire\n"
1374
1741
                     "      <n>  = key expires in n days\n"
1378
1745
        break;
1379
1746
 
1380
1747
      case 1:
 
1748
        if(!def_expire)
 
1749
          BUG();
1381
1750
        tty_printf(_("Please specify how long the signature should be valid.\n"
1382
1751
                     "         0 = signature does not expire\n"
1383
1752
                     "      <n>  = signature expires in n days\n"
1395
1764
     * date */
1396
1765
 
1397
1766
    answer = NULL;
1398
 
    for(;;) {
 
1767
    for(;;)
 
1768
      {
1399
1769
        u32 curtime=make_timestamp();
1400
1770
 
1401
 
        xfree (answer);
 
1771
        xfree(answer);
1402
1772
        if(object==0)
1403
1773
          answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1404
1774
        else
1405
 
          answer = cpr_get("siggen.valid",_("Signature is valid for? (0) "));
 
1775
          {
 
1776
            char *prompt;
 
1777
 
 
1778
#define PROMPTSTRING _("Signature is valid for? (%s) ")
 
1779
            /* This will actually end up larger than necessary because
 
1780
               of the 2 bytes for '%s' */
 
1781
            prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
 
1782
            sprintf(prompt,PROMPTSTRING,def_expire);
 
1783
#undef PROMPTSTRING
 
1784
 
 
1785
            answer = cpr_get("siggen.valid",prompt);
 
1786
            xfree(prompt);
 
1787
 
 
1788
            if(*answer=='\0')
 
1789
              answer=xstrdup(def_expire);
 
1790
          }
1406
1791
        cpr_kill_prompt();
1407
1792
        trim_spaces(answer);
1408
 
        valid_days = parse_expire_string( answer );
1409
 
        if( valid_days < 0 ) {
 
1793
        interval = parse_expire_string( answer );
 
1794
        if( interval == (u32)-1 )
 
1795
          {
1410
1796
            tty_printf(_("invalid value\n"));
1411
1797
            continue;
1412
 
        }
 
1798
          }
1413
1799
 
1414
 
        if( !valid_days ) {
1415
 
            tty_printf(_("%s does not expire at all\n"),
1416
 
                       object==0?"Key":"Signature");
1417
 
            interval = 0;
1418
 
        }
1419
 
        else {
1420
 
            interval = valid_days * 86400L;
1421
 
            /* print the date when the key expires */
1422
 
            tty_printf(_("%s expires at %s\n"),
1423
 
                        object==0?"Key":"Signature",
1424
 
                        asctimestamp((ulong)(curtime + interval) ) );
1425
 
            /* FIXME: This check yields warning some machines: write a
1426
 
               configure check and do this check here only for 32 bit
1427
 
               machines */
 
1800
        if( !interval )
 
1801
          {
 
1802
            tty_printf((object==0)
 
1803
                       ? _("Key does not expire at all\n")
 
1804
                       : _("Signature does not expire at all\n"));
 
1805
          }
 
1806
        else
 
1807
          {
 
1808
            tty_printf(object==0
 
1809
                       ? _("Key expires at %s\n")
 
1810
                       : _("Signature expires at %s\n"),
 
1811
                       asctimestamp((ulong)(curtime + interval) ) );
 
1812
            /* FIXME: This check yields warning on alhas: Write a
 
1813
               configure check and to this check here only for 32 bit
 
1814
               machines */
1428
1815
            if( (time_t)((ulong)(curtime+interval)) < 0 )
1429
 
                tty_printf(_("Your system can't display dates beyond 2038.\n"
1430
 
                    "However, it will be correctly handled up to 2106.\n"));
1431
 
        }
 
1816
              tty_printf(_("Your system can't display dates beyond 2038.\n"
 
1817
                           "However, it will be correctly handled up to 2106.\n"));
 
1818
          }
1432
1819
 
1433
1820
        if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1434
 
                                            _("Is this correct (y/n)? ")) )
1435
 
            break;
1436
 
    }
1437
 
    xfree (answer);
 
1821
                                                   _("Is this correct? (y/N) ")) )
 
1822
          break;
 
1823
      }
 
1824
 
 
1825
    xfree(answer);
1438
1826
    return interval;
1439
1827
}
1440
1828
 
1441
1829
u32
1442
1830
ask_expiredate()
1443
1831
{
1444
 
    u32 x = ask_expire_interval(0);
 
1832
    u32 x = ask_expire_interval(0,NULL);
1445
1833
    return x? make_timestamp() + x : 0;
1446
1834
}
1447
1835
 
1448
1836
 
1449
 
static int
1450
 
count_chr( const char *string, int c )
1451
 
{
1452
 
  int count;
1453
 
 
1454
 
  for (count=0; *string; string++ )
1455
 
    if ( *string == c )
1456
 
      count++;
1457
 
  return count;
1458
 
}
1459
 
 
1460
 
 
1461
 
static int
1462
 
has_invalid_email_chars( const char *s )
1463
 
{
1464
 
    int at_seen=0;
1465
 
    static char valid_chars[] = "01234567890_-."
1466
 
                                "abcdefghijklmnopqrstuvwxyz"
1467
 
                                "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1468
 
 
1469
 
    for( ; *s; s++ ) {
1470
 
        if( *s & 0x80 )
1471
 
            return 1;
1472
 
        if( *s == '@' )
1473
 
            at_seen=1;
1474
 
        else if( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1475
 
            return 1;
1476
 
        else if( at_seen && !strchr( valid_chars, *s ) )
1477
 
            return 1;
1478
 
    }
1479
 
    return 0;
1480
 
}
1481
 
 
1482
 
 
1483
1837
static char *
1484
1838
ask_user_id( int mode )
1485
1839
{
1488
1842
 
1489
1843
    if( !mode )
1490
1844
        tty_printf( _("\n"
1491
 
"You need a User-ID to identify your key; the software constructs the user id\n"
1492
 
"from Real Name, Comment and Email Address in this form:\n"
 
1845
"You need a user ID to identify your key; "
 
1846
                                        "the software constructs the user ID\n"
 
1847
"from the Real Name, Comment and Email Address in this form:\n"
1493
1848
"    \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n") );
1494
1849
    uid = aname = acomment = amail = NULL;
1495
1850
    for(;;) {
1498
1853
 
1499
1854
        if( !aname ) {
1500
1855
            for(;;) {
1501
 
                xfree (aname);
 
1856
                xfree(aname);
1502
1857
                aname = cpr_get("keygen.name",_("Real name: "));
1503
1858
                trim_spaces(aname);
1504
1859
                cpr_kill_prompt();
1518
1873
        }
1519
1874
        if( !amail ) {
1520
1875
            for(;;) {
1521
 
                xfree (amail);
 
1876
                xfree(amail);
1522
1877
                amail = cpr_get("keygen.email",_("Email address: "));
1523
1878
                trim_spaces(amail);
1524
1879
                cpr_kill_prompt();
1525
1880
                if( !*amail || opt.allow_freeform_uid )
1526
1881
                    break;   /* no email address is okay */
1527
 
                else if( has_invalid_email_chars(amail)
1528
 
                         || count_chr(amail,'@') != 1
1529
 
                         || *amail == '@'
1530
 
                         || amail[strlen(amail)-1] == '@'
1531
 
                         || amail[strlen(amail)-1] == '.'
1532
 
                         || strstr(amail, "..") )
1533
 
                    tty_printf(_("Not a valid email address\n"));
 
1882
                else if ( !is_valid_mailbox (amail) )
 
1883
                    tty_printf(_("Not a valid email address\n"));
1534
1884
                else
1535
1885
                    break;
1536
1886
            }
1537
1887
        }
1538
1888
        if( !acomment ) {
1539
1889
            for(;;) {
1540
 
                xfree (acomment);
 
1890
                xfree(acomment);
1541
1891
                acomment = cpr_get("keygen.comment",_("Comment: "));
1542
1892
                trim_spaces(acomment);
1543
1893
                cpr_kill_prompt();
1551
1901
        }
1552
1902
 
1553
1903
 
1554
 
        xfree (uid);
1555
 
        uid = p = xmalloc (strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
 
1904
        xfree(uid);
 
1905
        uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
1556
1906
        p = stpcpy(p, aname );
1557
1907
        if( *acomment )
1558
1908
            p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
1559
1909
        if( *amail )
1560
1910
            p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
1561
1911
 
 
1912
        /* append a warning if we do not have dev/random
 
1913
         * or it is switched into  quick testmode */
 
1914
        /* FIXME: see skclist.c:random_is_faked */
 
1915
        /*      if( quick_random_gen(-1)  ) */
 
1916
        /*          strcpy(p, " (INSECURE!)" ); */
 
1917
 
1562
1918
        /* print a note in case that UTF8 mapping has to be done */
1563
1919
        for(p=uid; *p; p++ ) {
1564
1920
            if( *p & 0x80 ) {
1571
1927
        tty_printf(_("You selected this USER-ID:\n    \"%s\"\n\n"), uid);
1572
1928
        /* fixme: add a warning if this user-id already exists */
1573
1929
        if( !*amail && !opt.allow_freeform_uid
1574
 
            && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
 
1930
            && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
1575
1931
            fail = 1;
1576
1932
            tty_printf(_("Please don't put the email address "
1577
1933
                          "into the real name or the comment\n") );
1578
1934
        }
1579
1935
 
1580
1936
        for(;;) {
 
1937
            /* TRANSLATORS: These are the allowed answers in
 
1938
               lower and uppercase.  Below you will find the matching
 
1939
               string which should be translated accordingly and the
 
1940
               letter changed to match the one in the answer string.
 
1941
               
 
1942
                 n = Change name
 
1943
                 c = Change comment
 
1944
                 e = Change email
 
1945
                 o = Okay (ready, continue)
 
1946
                 q = Quit
 
1947
             */
1581
1948
            const char *ansstr = _("NnCcEeOoQq");
1582
1949
 
1583
1950
            if( strlen(ansstr) != 10 )
1584
1951
                BUG();
1585
1952
            if( cpr_enabled() ) {
1586
 
                answer = xstrdup (ansstr+6);
 
1953
                answer = xstrdup(ansstr+6);
1587
1954
                answer[1] = 0;
1588
1955
            }
1589
1956
            else {
1595
1962
            if( strlen(answer) > 1 )
1596
1963
                ;
1597
1964
            else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
1598
 
                xfree (aname); aname = NULL;
 
1965
                xfree(aname); aname = NULL;
1599
1966
                break;
1600
1967
            }
1601
1968
            else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
1602
 
                xfree (acomment); acomment = NULL;
 
1969
                xfree(acomment); acomment = NULL;
1603
1970
                break;
1604
1971
            }
1605
1972
            else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
1606
 
                xfree (amail); amail = NULL;
 
1973
                xfree(amail); amail = NULL;
1607
1974
                break;
1608
1975
            }
1609
1976
            else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
1611
1978
                    tty_printf(_("Please correct the error first\n"));
1612
1979
                }
1613
1980
                else {
1614
 
                    xfree (aname); aname = NULL;
1615
 
                    xfree (acomment); acomment = NULL;
1616
 
                    xfree (amail); amail = NULL;
 
1981
                    xfree(aname); aname = NULL;
 
1982
                    xfree(acomment); acomment = NULL;
 
1983
                    xfree(amail); amail = NULL;
1617
1984
                    break;
1618
1985
                }
1619
1986
            }
1620
1987
            else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
1621
 
                xfree (aname); aname = NULL;
1622
 
                xfree (acomment); acomment = NULL;
1623
 
                xfree (amail); amail = NULL;
1624
 
                xfree (uid); uid = NULL;
 
1988
                xfree(aname); aname = NULL;
 
1989
                xfree(acomment); acomment = NULL;
 
1990
                xfree(amail); amail = NULL;
 
1991
                xfree(uid); uid = NULL;
1625
1992
                break;
1626
1993
            }
1627
 
            xfree (answer);
 
1994
            xfree(answer);
1628
1995
        }
1629
 
        xfree (answer);
 
1996
        xfree(answer);
1630
1997
        if( !amail && !acomment && !amail )
1631
 
          break;
1632
 
        xfree (uid); uid = NULL;
 
1998
            break;
 
1999
        xfree(uid); uid = NULL;
1633
2000
    }
1634
2001
    if( uid ) {
1635
2002
        char *p = native_to_utf8( uid );
1636
 
        xfree ( uid );
 
2003
        xfree( uid );
1637
2004
        uid = p;
1638
2005
    }
1639
2006
    return uid;
1640
2007
}
1641
2008
 
1642
2009
 
 
2010
/* FIXME: We need a way to cancel this prompt. */
1643
2011
static DEK *
1644
 
ask_passphrase( STRING2KEY **ret_s2k )
 
2012
do_ask_passphrase( STRING2KEY **ret_s2k )
1645
2013
{
1646
2014
    DEK *dek = NULL;
1647
2015
    STRING2KEY *s2k;
1649
2017
 
1650
2018
    tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
1651
2019
 
1652
 
    s2k = xmalloc ( sizeof *s2k );
 
2020
    s2k = xmalloc_secure( sizeof *s2k );
1653
2021
    for(;;) {
1654
2022
        s2k->mode = opt.s2k_mode;
1655
 
        s2k->hash_algo = opt.s2k_digest_algo;
 
2023
        s2k->hash_algo = S2K_DIGEST_ALGO;
1656
2024
        dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k,2,
1657
2025
                                 errtext, NULL);
1658
2026
        if( !dek ) {
1660
2028
            tty_printf(_("%s.\n"), _(errtext));
1661
2029
        }
1662
2030
        else if( !dek->keylen ) {
1663
 
            xfree (dek); dek = NULL;
1664
 
            xfree (s2k); s2k = NULL;
 
2031
            xfree(dek); dek = NULL;
 
2032
            xfree(s2k); s2k = NULL;
1665
2033
            tty_printf(_(
1666
2034
            "You don't want a passphrase - this is probably a *bad* idea!\n"
1667
2035
            "I will do it anyway.  You can change your passphrase at any time,\n"
1678
2046
 
1679
2047
static int
1680
2048
do_create( int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
1681
 
           DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk, u32 expiredate )
 
2049
           DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk, u32 expiredate,
 
2050
           int is_subkey )
1682
2051
{
1683
 
    int rc=0;
 
2052
  int rc=0;
1684
2053
 
1685
 
    if( !opt.batch )
1686
 
        tty_printf(_(
 
2054
  if( !opt.batch )
 
2055
    tty_printf(_(
1687
2056
"We need to generate a lot of random bytes. It is a good idea to perform\n"
1688
2057
"some other action (type on the keyboard, move the mouse, utilize the\n"
1689
2058
"disks) during the prime generation; this gives the random number\n"
1690
2059
"generator a better chance to gain enough entropy.\n") );
1691
2060
 
1692
 
    if( algo == PUBKEY_ALGO_ELGAMAL || algo == PUBKEY_ALGO_ELGAMAL_E )
1693
 
        rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1694
 
    else if( algo == PUBKEY_ALGO_DSA )
1695
 
        rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1696
 
    else if( algo == PUBKEY_ALGO_RSA )
1697
 
        rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1698
 
    else
1699
 
        BUG();
 
2061
  if( algo == PUBKEY_ALGO_ELGAMAL_E )
 
2062
    rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate,
 
2063
                 is_subkey);
 
2064
  else if( algo == PUBKEY_ALGO_DSA )
 
2065
    rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk, expiredate,
 
2066
                 is_subkey);
 
2067
  else if( algo == PUBKEY_ALGO_RSA )
 
2068
    rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate,
 
2069
                 is_subkey);
 
2070
  else
 
2071
    BUG();
1700
2072
 
1701
 
#ifdef ENABLE_COMMENT_PACKETS
1702
 
    if( !rc ) {
1703
 
        add_kbnode( pub_root,
1704
 
                make_comment_node("#created by GNUPG v" VERSION " ("
1705
 
                                            PRINTABLE_OS_NAME ")"));
1706
 
        add_kbnode( sec_root,
1707
 
                make_comment_node("#created by GNUPG v" VERSION " ("
1708
 
                                            PRINTABLE_OS_NAME ")"));
1709
 
    }
1710
 
#endif
1711
 
    return rc;
 
2073
  return rc;
1712
2074
}
1713
2075
 
1714
2076
 
1726
2088
    if( !p )
1727
2089
        return NULL;
1728
2090
    n = strlen(p);
1729
 
    uid = xcalloc (1, sizeof *uid + n - 1 );
 
2091
    uid = xmalloc_clear( sizeof *uid + n - 1 );
1730
2092
    uid->len = n;
1731
2093
    strcpy(uid->name, p);
1732
2094
    uid->ref = 1;
1742
2104
    for( ; r ; r = r2 ) {
1743
2105
        r2 = r->next;
1744
2106
        if( r->key == pPASSPHRASE_DEK )
1745
 
            xfree ( r->u.dek );
 
2107
            xfree( r->u.dek );
1746
2108
        else if( r->key == pPASSPHRASE_S2K )
1747
 
            xfree ( r->u.s2k );
 
2109
            xfree( r->u.s2k );
1748
2110
 
1749
 
        xfree (r);
 
2111
        xfree(r);
1750
2112
    }
1751
2113
}
1752
2114
 
1777
2139
    if( digitp( r->u.value ) )
1778
2140
        i = atoi( r->u.value );
1779
2141
    else
1780
 
        i = openpgp_pk_map_name ( r->u.value );
 
2142
        i = gcry_pk_map_name (r->u.value);
1781
2143
    if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
1782
2144
      i = 0; /* we don't want to allow generation of these algorithms */
1783
2145
    return i;
1814
2176
        }
1815
2177
    }
1816
2178
    r->u.usage = use;
1817
 
    return 0;
 
2179
    return 1;
1818
2180
}
1819
2181
 
1820
2182
static int
1917
2279
proc_parameter_file( struct para_data_s *para, const char *fname,
1918
2280
                     struct output_control_s *outctrl, int card )
1919
2281
{
1920
 
    struct para_data_s *r;
1921
 
    const char *s1, *s2, *s3;
1922
 
    size_t n;
1923
 
    char *p;
1924
 
    int i;
1925
 
 
1926
 
    /* check that we have all required parameters */
1927
 
    assert( get_parameter( para, pKEYTYPE ) );
1928
 
    i = get_parameter_algo( para, pKEYTYPE );
1929
 
    if( i < 1 || openpgp_pk_test_algo ( i, PUBKEY_USAGE_SIG ) ) {
1930
 
        r = get_parameter( para, pKEYTYPE );
1931
 
        log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
1932
 
        return -1;
1933
 
    }
1934
 
 
1935
 
    if (parse_parameter_usage (fname, para, pKEYUSAGE))
1936
 
        return -1;
1937
 
 
1938
 
    i = get_parameter_algo( para, pSUBKEYTYPE );
1939
 
    if( i > 0 && openpgp_pk_test_algo ( i, 0 ) ) {
1940
 
        r = get_parameter( para, pSUBKEYTYPE );
1941
 
        log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
1942
 
        return -1;
1943
 
    }
1944
 
    if (i > 0 && parse_parameter_usage (fname, para, pSUBKEYUSAGE))
1945
 
        return -1;
1946
 
 
1947
 
 
1948
 
    if( !get_parameter_value( para, pUSERID ) ) {
1949
 
        /* create the formatted user ID */
1950
 
        s1 = get_parameter_value( para, pNAMEREAL );
1951
 
        s2 = get_parameter_value( para, pNAMECOMMENT );
1952
 
        s3 = get_parameter_value( para, pNAMEEMAIL );
1953
 
        if( s1 || s2 || s3 ) {
1954
 
            n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
1955
 
            r = xcalloc (1, sizeof *r + n + 20 );
1956
 
            r->key = pUSERID;
1957
 
            p = r->u.value;
1958
 
            if( s1 )
1959
 
                p = stpcpy(p, s1 );
1960
 
            if( s2 )
1961
 
                p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
1962
 
            if( s3 )
1963
 
                p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
1964
 
            r->next = para;
1965
 
            para = r;
1966
 
        }
1967
 
    }
1968
 
 
1969
 
    /* Set preferences, if any. */
1970
 
    keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
1971
 
 
1972
 
    /* Set revoker, if any. */
1973
 
    if (parse_revocation_key (fname, para, pREVOKER))
1974
 
      return -1;
1975
 
 
1976
 
    /* make DEK and S2K from the Passphrase */
1977
 
    r = get_parameter( para, pPASSPHRASE );
1978
 
    if( r && *r->u.value ) {
1979
 
        /* we have a plain text passphrase - create a DEK from it.
1980
 
         * It is a little bit ridiculous to keep it in secure memory
1981
 
         * but because we do this always, why not here. */
1982
 
        STRING2KEY *s2k;
1983
 
        DEK *dek;
1984
 
 
1985
 
        s2k = xmalloc_secure ( sizeof *s2k );
1986
 
        s2k->mode = opt.s2k_mode;
1987
 
        s2k->hash_algo = opt.s2k_digest_algo;
1988
 
        set_next_passphrase( r->u.value );
1989
 
        dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2,
1990
 
                                 NULL, NULL);
1991
 
        set_next_passphrase( NULL );
1992
 
        assert( dek );
1993
 
        memset( r->u.value, 0, strlen(r->u.value) );
1994
 
 
1995
 
        r = xcalloc (1, sizeof *r );
1996
 
        r->key = pPASSPHRASE_S2K;
1997
 
        r->u.s2k = s2k;
1998
 
        r->next = para;
1999
 
        para = r;
2000
 
        r = xcalloc (1, sizeof *r );
2001
 
        r->key = pPASSPHRASE_DEK;
2002
 
        r->u.dek = dek;
2003
 
        r->next = para;
2004
 
        para = r;
2005
 
    }
2006
 
 
2007
 
    /* make KEYEXPIRE from Expire-Date */
2008
 
    r = get_parameter( para, pEXPIREDATE );
2009
 
    if( r && *r->u.value ) {
2010
 
        i = parse_expire_string( r->u.value );
2011
 
        if( i < 0 ) {
2012
 
            log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2013
 
            return -1;
2014
 
        }
2015
 
        r->u.expire = i * 86400L;
2016
 
        r->key = pKEYEXPIRE;  /* change hat entry */
2017
 
        /* also set it for the subkey */
2018
 
        r = xcalloc (1, sizeof *r + 20 );
2019
 
        r->key = pSUBKEYEXPIRE;
2020
 
        r->u.expire = i * 86400L;
2021
 
        r->next = para;
2022
 
        para = r;
2023
 
    }
2024
 
 
2025
 
    if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2026
 
        log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2027
 
        return -1;
2028
 
    }
2029
 
 
2030
 
    do_generate_keypair( para, outctrl, card);
2031
 
    return 0;
 
2282
  struct para_data_s *r;
 
2283
  const char *s1, *s2, *s3;
 
2284
  size_t n;
 
2285
  char *p;
 
2286
  int have_user_id=0,err,algo;
 
2287
 
 
2288
  /* Check that we have all required parameters. */
 
2289
  r = get_parameter( para, pKEYTYPE );
 
2290
  if(r)
 
2291
    {
 
2292
      algo=get_parameter_algo(para,pKEYTYPE);
 
2293
      if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
 
2294
        {
 
2295
          log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
 
2296
          return -1;
 
2297
        }
 
2298
    }
 
2299
  else
 
2300
    {
 
2301
      log_error("%s: no Key-Type specified\n",fname);
 
2302
      return -1;
 
2303
    }
 
2304
 
 
2305
  err=parse_parameter_usage (fname, para, pKEYUSAGE);
 
2306
  if(err==0)
 
2307
    {
 
2308
      /* Default to algo capabilities if key-usage is not provided */
 
2309
      r=xmalloc_clear(sizeof(*r));
 
2310
      r->key=pKEYUSAGE;
 
2311
      r->u.usage=openpgp_pk_algo_usage(algo);
 
2312
      r->next=para;
 
2313
      para=r;
 
2314
    }
 
2315
  else if(err==-1)
 
2316
    return -1;
 
2317
 
 
2318
  r = get_parameter( para, pSUBKEYTYPE );
 
2319
  if(r)
 
2320
    {
 
2321
      algo=get_parameter_algo( para, pSUBKEYTYPE);
 
2322
      if (openpgp_pk_test_algo (algo))
 
2323
        {
 
2324
          log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
 
2325
          return -1;
 
2326
        }
 
2327
 
 
2328
      err=parse_parameter_usage (fname, para, pSUBKEYUSAGE);
 
2329
      if(err==0)
 
2330
        {
 
2331
          /* Default to algo capabilities if subkey-usage is not
 
2332
             provided */
 
2333
          r=xmalloc_clear(sizeof(*r));
 
2334
          r->key=pSUBKEYUSAGE;
 
2335
          r->u.usage=openpgp_pk_algo_usage(algo);
 
2336
          r->next=para;
 
2337
          para=r;
 
2338
        }
 
2339
      else if(err==-1)
 
2340
        return -1;
 
2341
    }
 
2342
 
 
2343
  if( get_parameter_value( para, pUSERID ) )
 
2344
    have_user_id=1;
 
2345
  else
 
2346
    {
 
2347
      /* create the formatted user ID */
 
2348
      s1 = get_parameter_value( para, pNAMEREAL );
 
2349
      s2 = get_parameter_value( para, pNAMECOMMENT );
 
2350
      s3 = get_parameter_value( para, pNAMEEMAIL );
 
2351
      if( s1 || s2 || s3 )
 
2352
        {
 
2353
          n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
 
2354
          r = xmalloc_clear( sizeof *r + n + 20 );
 
2355
          r->key = pUSERID;
 
2356
          p = r->u.value;
 
2357
          if( s1 )
 
2358
            p = stpcpy(p, s1 );
 
2359
          if( s2 )
 
2360
            p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
 
2361
          if( s3 )
 
2362
            p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
 
2363
          r->next = para;
 
2364
          para = r;
 
2365
          have_user_id=1;
 
2366
        }
 
2367
    }
 
2368
 
 
2369
  if(!have_user_id)
 
2370
    {
 
2371
      log_error("%s: no User-ID specified\n",fname);
 
2372
      return -1;
 
2373
    }
 
2374
 
 
2375
  /* Set preferences, if any. */
 
2376
  keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
 
2377
 
 
2378
  /* Set revoker, if any. */
 
2379
  if (parse_revocation_key (fname, para, pREVOKER))
 
2380
    return -1;
 
2381
 
 
2382
  /* make DEK and S2K from the Passphrase */
 
2383
  r = get_parameter( para, pPASSPHRASE );
 
2384
  if( r && *r->u.value ) {
 
2385
    /* we have a plain text passphrase - create a DEK from it.
 
2386
     * It is a little bit ridiculous to keep it ih secure memory
 
2387
     * but becuase we do this alwasy, why not here */
 
2388
    STRING2KEY *s2k;
 
2389
    DEK *dek;
 
2390
 
 
2391
    s2k = xmalloc_secure( sizeof *s2k );
 
2392
    s2k->mode = opt.s2k_mode;
 
2393
    s2k->hash_algo = S2K_DIGEST_ALGO;
 
2394
    set_next_passphrase( r->u.value );
 
2395
    dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2,
 
2396
                             NULL, NULL);
 
2397
    set_next_passphrase( NULL );
 
2398
    assert( dek );
 
2399
    memset( r->u.value, 0, strlen(r->u.value) );
 
2400
 
 
2401
    r = xmalloc_clear( sizeof *r );
 
2402
    r->key = pPASSPHRASE_S2K;
 
2403
    r->u.s2k = s2k;
 
2404
    r->next = para;
 
2405
    para = r;
 
2406
    r = xmalloc_clear( sizeof *r );
 
2407
    r->key = pPASSPHRASE_DEK;
 
2408
    r->u.dek = dek;
 
2409
    r->next = para;
 
2410
    para = r;
 
2411
  }
 
2412
 
 
2413
  /* make KEYEXPIRE from Expire-Date */
 
2414
  r = get_parameter( para, pEXPIREDATE );
 
2415
  if( r && *r->u.value )
 
2416
    {
 
2417
      u32 seconds;
 
2418
 
 
2419
      seconds = parse_expire_string( r->u.value );
 
2420
      if( seconds == (u32)-1 )
 
2421
        {
 
2422
          log_error("%s:%d: invalid expire date\n", fname, r->lnr );
 
2423
          return -1;
 
2424
        }
 
2425
      r->u.expire = seconds;
 
2426
      r->key = pKEYEXPIRE;  /* change hat entry */
 
2427
      /* also set it for the subkey */
 
2428
      r = xmalloc_clear( sizeof *r + 20 );
 
2429
      r->key = pSUBKEYEXPIRE;
 
2430
      r->u.expire = seconds;
 
2431
      r->next = para;
 
2432
      para = r;
 
2433
    }
 
2434
 
 
2435
  if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
 
2436
    log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
 
2437
    return -1;
 
2438
  }
 
2439
 
 
2440
  do_generate_keypair( para, outctrl, card );
 
2441
  return 0;
2032
2442
}
2033
2443
 
2034
2444
 
2035
2445
/****************
2036
2446
 * Kludge to allow non interactive key generation controlled
2037
 
 * by a parameter file (which currently is only stdin)
 
2447
 * by a parameter file.
2038
2448
 * Note, that string parameters are expected to be in UTF-8
2039
2449
 */
2040
2450
static void
2056
2466
        { "Passphrase",     pPASSPHRASE },
2057
2467
        { "Preferences",    pPREFERENCES },
2058
2468
        { "Revoker",        pREVOKER },
 
2469
        { "Handle",         pHANDLE },
2059
2470
        { NULL, 0 }
2060
2471
    };
2061
 
    FILE *fp;
2062
 
    char line[1024], *p;
 
2472
    IOBUF fp;
 
2473
    byte *line;
 
2474
    unsigned int maxlen, nline;
 
2475
    char *p;
2063
2476
    int lnr;
2064
2477
    const char *err = NULL;
2065
2478
    struct para_data_s *para, *r;
2068
2481
 
2069
2482
    memset( &outctrl, 0, sizeof( outctrl ) );
2070
2483
 
2071
 
    if( !fname || !*fname || !strcmp(fname,"-") ) {
2072
 
        fp = stdin;
2073
 
        fname = "-";
2074
 
    }
2075
 
    else {
2076
 
        fp = fopen( fname, "r" );
2077
 
        if( !fp ) {
2078
 
            log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
2079
 
            return;
2080
 
        }
2081
 
    }
 
2484
    if( !fname || !*fname)
 
2485
      fname = "-";
 
2486
 
 
2487
    fp = iobuf_open (fname);
 
2488
    if (fp && is_secured_file (iobuf_get_fd (fp)))
 
2489
      {
 
2490
        iobuf_close (fp);
 
2491
        fp = NULL;
 
2492
        errno = EPERM;
 
2493
      }
 
2494
    if (!fp) {
 
2495
      log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
 
2496
      return;
 
2497
    }
 
2498
    iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2082
2499
 
2083
2500
    lnr = 0;
2084
2501
    err = NULL;
2085
2502
    para = NULL;
2086
 
    while( fgets( line, DIM(line)-1, fp ) ) {
 
2503
    maxlen = 1024;
 
2504
    line = NULL;
 
2505
    while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2087
2506
        char *keyword, *value;
2088
2507
 
2089
2508
        lnr++;
2090
 
        if( *line && line[strlen(line)-1] != '\n' ) {
 
2509
        if( !maxlen ) {
2091
2510
            err = "line too long";
2092
2511
            break;
2093
2512
        }
2111
2530
                outctrl.dryrun = 1;
2112
2531
            else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2113
2532
                outctrl.lnr = lnr;
2114
 
                proc_parameter_file( para, fname, &outctrl, 0 );
 
2533
                if (proc_parameter_file( para, fname, &outctrl, 0 ))
 
2534
                  print_status_key_not_created 
 
2535
                    (get_parameter_value (para, pHANDLE));
2115
2536
                release_parameter_list( para );
2116
2537
                para = NULL;
2117
2538
            }
2119
2540
                if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2120
2541
                    ; /* still the same file - ignore it */
2121
2542
                else {
2122
 
                    xfree ( outctrl.pub.newfname );
2123
 
                    outctrl.pub.newfname = xstrdup ( value );
 
2543
                    xfree( outctrl.pub.newfname );
 
2544
                    outctrl.pub.newfname = xstrdup( value );
2124
2545
                    outctrl.use_files = 1;
2125
2546
                }
2126
2547
            }
2128
2549
                if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2129
2550
                    ; /* still the same file - ignore it */
2130
2551
                else {
2131
 
                   xfree ( outctrl.sec.newfname );
2132
 
                   outctrl.sec.newfname = xstrdup ( value );
 
2552
                   xfree( outctrl.sec.newfname );
 
2553
                   outctrl.sec.newfname = xstrdup( value );
2133
2554
                   outctrl.use_files = 1;
2134
2555
                }
2135
2556
            }
2171
2592
 
2172
2593
        if( keywords[i].key == pKEYTYPE && para ) {
2173
2594
            outctrl.lnr = lnr;
2174
 
            proc_parameter_file( para, fname, &outctrl, 0 );
 
2595
            if (proc_parameter_file( para, fname, &outctrl, 0 ))
 
2596
              print_status_key_not_created
 
2597
                (get_parameter_value (para, pHANDLE));
2175
2598
            release_parameter_list( para );
2176
2599
            para = NULL;
2177
2600
        }
2185
2608
                break;
2186
2609
            }
2187
2610
        }
2188
 
        r = xcalloc (1, sizeof *r + strlen( value ) );
 
2611
        r = xmalloc_clear( sizeof *r + strlen( value ) );
2189
2612
        r->lnr = lnr;
2190
2613
        r->key = keywords[i].key;
2191
2614
        strcpy( r->u.value, value );
2194
2617
    }
2195
2618
    if( err )
2196
2619
        log_error("%s:%d: %s\n", fname, lnr, err );
2197
 
    else if( ferror(fp) ) {
2198
 
        log_error("%s:%d: read error: %s\n", fname, lnr, strerror(errno) );
 
2620
    else if( iobuf_error (fp) ) {
 
2621
        log_error("%s:%d: read error\n", fname, lnr);
2199
2622
    }
2200
2623
    else if( para ) {
2201
2624
        outctrl.lnr = lnr;
2202
 
        proc_parameter_file( para, fname, &outctrl, 0 );
 
2625
        if (proc_parameter_file( para, fname, &outctrl, 0 ))
 
2626
          print_status_key_not_created (get_parameter_value (para, pHANDLE));
2203
2627
    }
2204
2628
 
2205
2629
    if( outctrl.use_files ) { /* close open streams */
2206
2630
        iobuf_close( outctrl.pub.stream );
2207
2631
        iobuf_close( outctrl.sec.stream );
2208
 
        xfree ( outctrl.pub.fname );
2209
 
        xfree ( outctrl.pub.newfname );
2210
 
        xfree ( outctrl.sec.fname );
2211
 
        xfree ( outctrl.sec.newfname );
 
2632
 
 
2633
        /* Must invalidate that ugly cache to actually close it.  */
 
2634
        if (outctrl.pub.fname)
 
2635
          iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
 
2636
        if (outctrl.sec.fname)
 
2637
          iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
 
2638
 
 
2639
        xfree( outctrl.pub.fname );
 
2640
        xfree( outctrl.pub.newfname );
 
2641
        xfree( outctrl.sec.fname );
 
2642
        xfree( outctrl.sec.newfname );
2212
2643
    }
2213
2644
 
2214
2645
    release_parameter_list( para );
2215
 
    if( strcmp( fname, "-" ) )
2216
 
        fclose(fp);
 
2646
    iobuf_close (fp);
2217
2647
}
2218
2648
 
2219
2649
 
2220
 
/****************
 
2650
/*
2221
2651
 * Generate a keypair (fname is only used in batch mode) If
2222
 
 * CARD_SERIALNO is not NULL the fucntion will create the keys on an
2223
 
 * OpenPGP Card.
 
2652
 * CARD_SERIALNO is not NULL the function will create the keys on an
 
2653
 * OpenPGP Card.  If BACKUP_ENCRYPTION_DIR has been set and
 
2654
 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
 
2655
 * generate in software, imported to the card and a backup file
 
2656
 * written to directory given by this argument .
2224
2657
 */
2225
2658
void
2226
 
generate_keypair( const char *fname, const char *card_serialno )
 
2659
generate_keypair (const char *fname, const char *card_serialno, 
 
2660
                  const char *backup_encryption_dir)
2227
2661
{
2228
2662
  unsigned int nbits;
2229
2663
  char *uid = NULL;
2236
2670
  struct para_data_s *para = NULL;
2237
2671
  struct para_data_s *r;
2238
2672
  struct output_control_s outctrl;
2239
 
 
2240
 
  memset (&outctrl, 0, sizeof (outctrl));
2241
 
 
 
2673
  
 
2674
  memset( &outctrl, 0, sizeof( outctrl ) );
 
2675
  
2242
2676
  if (opt.batch && card_serialno)
2243
2677
    {
2244
2678
      /* We don't yet support unattended key generation. */
2245
 
      log_error (_("sorry, can't do this in batch mode\n"));
 
2679
      log_error (_("can't do this in batch mode\n"));
2246
2680
      return;
2247
2681
    }
2248
 
 
 
2682
  
2249
2683
  if (opt.batch)
2250
2684
    {
2251
2685
      read_parameter_file( fname );
2254
2688
 
2255
2689
  if (card_serialno)
2256
2690
    {
 
2691
#ifdef ENABLE_CARD_SUPPORT
2257
2692
      r = xcalloc (1, sizeof *r + strlen (card_serialno) );
2258
2693
      r->key = pSERIALNO;
2259
2694
      strcpy( r->u.value, card_serialno);
2260
2695
      r->next = para;
2261
2696
      para = r;
2262
 
 
 
2697
       
2263
2698
      algo = PUBKEY_ALGO_RSA;
2264
 
 
 
2699
       
2265
2700
      r = xcalloc (1, sizeof *r + 20 );
2266
2701
      r->key = pKEYTYPE;
2267
2702
      sprintf( r->u.value, "%d", algo );
2272
2707
      strcpy (r->u.value, "sign");
2273
2708
      r->next = para;
2274
2709
      para = r;
2275
 
 
 
2710
       
2276
2711
      r = xcalloc (1, sizeof *r + 20 );
2277
2712
      r->key = pSUBKEYTYPE;
2278
2713
      sprintf( r->u.value, "%d", algo );
2283
2718
      strcpy (r->u.value, "encrypt");
2284
2719
      r->next = para;
2285
2720
      para = r;
2286
 
 
 
2721
       
2287
2722
      r = xcalloc (1, sizeof *r + 20 );
2288
2723
      r->key = pAUTHKEYTYPE;
2289
2724
      sprintf( r->u.value, "%d", algo );
2290
2725
      r->next = para;
2291
2726
      para = r;
 
2727
 
 
2728
      if (backup_encryption_dir)
 
2729
        {
 
2730
          r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
 
2731
          r->key = pBACKUPENCDIR;
 
2732
          strcpy (r->u.value, backup_encryption_dir);
 
2733
          r->next = para;
 
2734
          para = r;
 
2735
        }
 
2736
#endif /*ENABLE_CARD_SUPPORT*/
2292
2737
    }
2293
2738
  else
2294
2739
    {
2295
 
      algo = ask_algo (0, &use);
2296
 
      
2297
 
      if (!algo)
 
2740
      algo = ask_algo( 0, &use );
 
2741
      if( !algo )
2298
2742
        { /* default: DSA with ElG subkey of the specified size */
2299
2743
          both = 1;
2300
 
          r = xcalloc (1, sizeof *r + 20 );
 
2744
          r = xmalloc_clear( sizeof *r + 20 );
2301
2745
          r->key = pKEYTYPE;
2302
2746
          sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
2303
2747
          r->next = para;
2304
2748
          para = r;
2305
 
          tty_printf(_("DSA keypair will have 1024 bits.\n"));
2306
 
          r = xcalloc (1, sizeof *r + 20 );
 
2749
          tty_printf(_("DSA keypair will have %u bits.\n"),1024);
 
2750
          r = xmalloc_clear( sizeof *r + 20 );
2307
2751
          r->key = pKEYLENGTH;
2308
2752
          strcpy( r->u.value, "1024" );
2309
2753
          r->next = para;
2310
2754
          para = r;
2311
 
          r = xcalloc (1, sizeof *r + 20 );
 
2755
          r = xmalloc_clear( sizeof *r + 20 );
2312
2756
          r->key = pKEYUSAGE;
2313
2757
          strcpy( r->u.value, "sign" );
2314
2758
          r->next = para;
2315
2759
          para = r;
2316
 
          
 
2760
           
2317
2761
          algo = PUBKEY_ALGO_ELGAMAL_E;
2318
 
          r = xcalloc (1, sizeof *r + 20 );
 
2762
          r = xmalloc_clear( sizeof *r + 20 );
2319
2763
          r->key = pSUBKEYTYPE;
2320
2764
          sprintf( r->u.value, "%d", algo );
2321
2765
          r->next = para;
2322
2766
          para = r;
2323
 
          r = xcalloc (1, sizeof *r + 20 );
 
2767
          r = xmalloc_clear( sizeof *r + 20 );
2324
2768
          r->key = pSUBKEYUSAGE;
2325
2769
          strcpy( r->u.value, "encrypt" );
2326
2770
          r->next = para;
2327
 
          r->next = para;
2328
2771
          para = r;
2329
2772
        }
2330
2773
      else 
2331
2774
        {
2332
 
          r = xcalloc (1, sizeof *r + 20 );
 
2775
          r = xmalloc_clear( sizeof *r + 20 );
2333
2776
          r->key = pKEYTYPE;
2334
2777
          sprintf( r->u.value, "%d", algo );
2335
2778
          r->next = para;
2336
2779
          para = r;
2337
 
          
 
2780
           
2338
2781
          if (use)
2339
2782
            {
2340
 
              r = xcalloc (1, sizeof *r + 20 );
 
2783
              r = xmalloc_clear( sizeof *r + 25 );
2341
2784
              r->key = pKEYUSAGE;
2342
 
              sprintf( r->u.value, "%s%s",
 
2785
              sprintf( r->u.value, "%s%s%s",
2343
2786
                       (use & PUBKEY_USAGE_SIG)? "sign ":"",
2344
 
                       (use & PUBKEY_USAGE_ENC)? "encrypt ":"" );
 
2787
                       (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
 
2788
                       (use & PUBKEY_USAGE_AUTH)? "auth":"" );
2345
2789
              r->next = para;
2346
2790
              para = r;
2347
2791
            }
 
2792
           
2348
2793
        }
2349
 
 
 
2794
       
2350
2795
      nbits = ask_keysize( algo );
2351
 
      r = xcalloc (1, sizeof *r + 20 );
 
2796
      r = xmalloc_clear( sizeof *r + 20 );
2352
2797
      r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
2353
2798
      sprintf( r->u.value, "%u", nbits);
2354
2799
      r->next = para;
2355
2800
      para = r;
2356
2801
    }
2357
 
 
2358
 
  expire = ask_expire_interval(0);
2359
 
  r = xcalloc (1, sizeof *r + 20 );
 
2802
   
 
2803
  expire = ask_expire_interval(0,NULL);
 
2804
  r = xmalloc_clear( sizeof *r + 20 );
2360
2805
  r->key = pKEYEXPIRE;
2361
2806
  r->u.expire = expire;
2362
2807
  r->next = para;
2363
2808
  para = r;
2364
 
  r = xcalloc (1, sizeof *r + 20 );
 
2809
  r = xmalloc_clear( sizeof *r + 20 );
2365
2810
  r->key = pSUBKEYEXPIRE;
2366
2811
  r->u.expire = expire;
2367
2812
  r->next = para;
2368
2813
  para = r;
2369
 
  
 
2814
 
2370
2815
  uid = ask_user_id(0);
2371
 
  if (!uid)
 
2816
  if( !uid ) 
2372
2817
    {
2373
2818
      log_error(_("Key generation canceled.\n"));
2374
2819
      release_parameter_list( para );
2375
2820
      return;
2376
2821
    }
2377
 
  r = xcalloc (1, sizeof *r + strlen(uid) );
 
2822
  r = xmalloc_clear( sizeof *r + strlen(uid) );
2378
2823
  r->key = pUSERID;
2379
2824
  strcpy( r->u.value, uid );
2380
2825
  r->next = para;
2381
2826
  para = r;
2382
 
 
2383
 
  dek = card_serialno? NULL : ask_passphrase( &s2k );
2384
 
  if (dek)
 
2827
    
 
2828
  dek = card_serialno? NULL : do_ask_passphrase( &s2k );
 
2829
  if( dek )
2385
2830
    {
2386
 
      r = xcalloc (1, sizeof *r );
 
2831
      r = xmalloc_clear( sizeof *r );
2387
2832
      r->key = pPASSPHRASE_DEK;
2388
2833
      r->u.dek = dek;
2389
2834
      r->next = para;
2390
2835
      para = r;
2391
 
      r = xcalloc (1, sizeof *r );
 
2836
      r = xmalloc_clear( sizeof *r );
2392
2837
      r->key = pPASSPHRASE_S2K;
2393
2838
      r->u.s2k = s2k;
2394
2839
      r->next = para;
2395
2840
      para = r;
2396
2841
    }
2397
 
  
2398
 
  proc_parameter_file (para, "[internal]", &outctrl, !!card_serialno);
2399
 
  release_parameter_list (para);
2400
 
}
2401
 
 
2402
 
 
2403
 
static void
2404
 
print_status_key_created (int letter, PKT_public_key *pk)
2405
 
{
2406
 
  byte array[MAX_FINGERPRINT_LEN], *s;
2407
 
  char buf[MAX_FINGERPRINT_LEN*2+30], *p;
2408
 
  size_t i, n;
2409
 
  
2410
 
  p = buf;
2411
 
  *p++ = letter;
2412
 
  *p++ = ' ';
2413
 
  fingerprint_from_pk (pk, array, &n);
2414
 
  s = array;
2415
 
  for (i=0; i < n ; i++, s++, p += 2)
2416
 
    sprintf (p, "%02X", *s);
2417
 
  *p = 0;
2418
 
  write_status_text (STATUS_KEY_CREATED, buf);
2419
 
}
2420
 
 
2421
 
 
2422
 
 
2423
 
static void
2424
 
do_generate_keypair (struct para_data_s *para,
2425
 
                     struct output_control_s *outctrl, int card)
2426
 
{
2427
 
  KBNODE pub_root = NULL;
2428
 
  KBNODE sec_root = NULL;
 
2842
    
 
2843
  proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
 
2844
  release_parameter_list( para );
 
2845
}
 
2846
 
 
2847
 
 
2848
#ifdef ENABLE_CARD_SUPPORT
 
2849
/* Generate a raw key and return it as a secret key packet.  The
 
2850
   function will ask for the passphrase and return a protected as well
 
2851
   as an unprotected copy of a new secret key packet.  0 is returned
 
2852
   on success and the caller must then free the returned values.  */
 
2853
static int
 
2854
generate_raw_key (int algo, unsigned int nbits, u32 created_at,
 
2855
                  PKT_secret_key **r_sk_unprotected,
 
2856
                  PKT_secret_key **r_sk_protected)
 
2857
{
 
2858
  int rc;
 
2859
  DEK *dek = NULL;
 
2860
  STRING2KEY *s2k = NULL;
2429
2861
  PKT_secret_key *sk = NULL;
2430
 
  const char *s;
2431
 
  struct revocation_key *revkey;
2432
 
  int rc;
2433
 
  int did_sub = 0;
2434
 
 
2435
 
  if (outctrl->dryrun)
2436
 
    {
2437
 
      log_info ("dry-run mode - key generation skipped\n");
2438
 
      return;
2439
 
    }
2440
 
 
2441
 
 
2442
 
  if (outctrl->use_files)
2443
 
    {
2444
 
      if (outctrl->pub.newfname)
2445
 
        {
2446
 
          iobuf_close (outctrl->pub.stream);
2447
 
          outctrl->pub.stream = NULL;
2448
 
          xfree (outctrl->pub.fname);
2449
 
          outctrl->pub.fname = outctrl->pub.newfname;
2450
 
          outctrl->pub.newfname = NULL;
2451
 
 
2452
 
          outctrl->pub.stream = iobuf_create (outctrl->pub.fname);
2453
 
          if (!outctrl->pub.stream)
2454
 
            {
2455
 
              log_error ("can't create `%s': %s\n", outctrl->pub.fname,
2456
 
                         strerror (errno));
2457
 
              return;
2458
 
            }
2459
 
          if (opt.armor)
2460
 
            {
2461
 
              outctrl->pub.afx.what = 1;
2462
 
              iobuf_push_filter (outctrl->pub.stream, armor_filter,
2463
 
                                 &outctrl->pub.afx);
2464
 
            }
2465
 
        }
2466
 
      if (outctrl->sec.newfname)
2467
 
        {
2468
 
          iobuf_close (outctrl->sec.stream);
2469
 
          outctrl->sec.stream = NULL;
2470
 
          xfree (outctrl->sec.fname);
2471
 
          outctrl->sec.fname = outctrl->sec.newfname;
2472
 
          outctrl->sec.newfname = NULL;
2473
 
 
2474
 
          outctrl->sec.stream = iobuf_create (outctrl->sec.fname);
2475
 
          if (!outctrl->sec.stream)
2476
 
            {
2477
 
              log_error ("can't create `%s': %s\n", outctrl->sec.fname,
2478
 
                         strerror (errno));
2479
 
              return;
2480
 
            }
2481
 
          if (opt.armor)
2482
 
            {
2483
 
              outctrl->sec.afx.what = 5;
2484
 
              iobuf_push_filter (outctrl->sec.stream, armor_filter,
2485
 
                                 &outctrl->sec.afx);
2486
 
            }
2487
 
        }
2488
 
      assert (outctrl->pub.stream);
2489
 
      assert (outctrl->sec.stream);
2490
 
      if (opt.verbose)
2491
 
        {
2492
 
          log_info (_("writing public key to `%s'\n"), outctrl->pub.fname);
2493
 
          if (card)
2494
 
            log_info (_("writing secret key stub to `%s'\n"),
2495
 
                      outctrl->sec.fname);
2496
 
          else
2497
 
            log_info (_("writing secret key to `%s'\n"), outctrl->sec.fname);
2498
 
        }
2499
 
    }
2500
 
 
2501
 
 
2502
 
  /* We create the packets as a tree of kbnodes. Because the structure
2503
 
   * we create is known in advance we simply generate a linked list.
2504
 
   * The first packet is a dummy comment packet which we flag
2505
 
   * as deleted.  The very first packet must always be a KEY packet.
2506
 
   */
2507
 
  pub_root = make_comment_node ("#");
2508
 
  delete_kbnode (pub_root);
2509
 
  sec_root = make_comment_node ("#");
2510
 
  delete_kbnode (sec_root);
2511
 
  if (!card)
2512
 
    {
2513
 
      rc = do_create (get_parameter_algo (para, pKEYTYPE),
2514
 
                      get_parameter_uint (para, pKEYLENGTH),
2515
 
                      pub_root, sec_root,
2516
 
                      get_parameter_dek (para, pPASSPHRASE_DEK),
2517
 
                      get_parameter_s2k (para, pPASSPHRASE_S2K),
2518
 
                      &sk, get_parameter_u32 (para, pKEYEXPIRE));
2519
 
    }
2520
 
  else
2521
 
    {
2522
 
      rc = gen_card_key (PUBKEY_ALGO_RSA, 1, pub_root, sec_root,
2523
 
                         get_parameter_u32 (para, pKEYEXPIRE), para);
2524
 
      if (!rc)
2525
 
        {
2526
 
          sk = sec_root->next->pkt->pkt.secret_key;
2527
 
          assert (sk);
2528
 
        }
2529
 
      
2530
 
    }
2531
 
 
2532
 
  if (!rc && (revkey = get_parameter_revkey (para, pREVOKER)))
2533
 
    {
2534
 
      rc = write_direct_sig (pub_root, pub_root, sk, revkey);
2535
 
      if (!rc)
2536
 
        write_direct_sig (sec_root, pub_root, sk, revkey);
2537
 
    }
2538
 
 
2539
 
  if (!rc && (s = get_parameter_value (para, pUSERID)))
2540
 
    {
2541
 
      write_uid (pub_root, s);
2542
 
      if (!rc)
2543
 
        write_uid (sec_root, s);
2544
 
      if (!rc)
2545
 
        rc = write_selfsig (pub_root, pub_root, sk,
2546
 
                            get_parameter_uint (para, pKEYUSAGE));
2547
 
      if (!rc)
2548
 
        rc = write_selfsig (sec_root, pub_root, sk,
2549
 
                            get_parameter_uint (para, pKEYUSAGE));
2550
 
    }
2551
 
 
2552
 
  if ((! rc) && get_parameter (para, pSUBKEYTYPE))
2553
 
    {
2554
 
      if (!card)
2555
 
        {
2556
 
          rc = do_create (get_parameter_algo (para, pSUBKEYTYPE),
2557
 
                          get_parameter_uint (para, pSUBKEYLENGTH),
2558
 
                          pub_root, sec_root,
2559
 
                          get_parameter_dek (para, pPASSPHRASE_DEK),
2560
 
                          get_parameter_s2k (para, pPASSPHRASE_S2K),
2561
 
                          NULL, get_parameter_u32 (para, pSUBKEYEXPIRE));
2562
 
        }
2563
 
      else
2564
 
        {
2565
 
          rc = gen_card_key (PUBKEY_ALGO_RSA, 2, pub_root, sec_root,
2566
 
                             get_parameter_u32 (para, pKEYEXPIRE), para);
2567
 
        }
2568
 
 
2569
 
      if (!rc)
2570
 
        rc = write_keybinding (pub_root, pub_root, sk,
2571
 
                               get_parameter_uint (para, pSUBKEYUSAGE));
2572
 
      if (!rc)
2573
 
        rc = write_keybinding (sec_root, pub_root, sk,
2574
 
                               get_parameter_uint (para, pSUBKEYUSAGE));
2575
 
      did_sub = 1;
2576
 
    }
2577
 
 
2578
 
  if ((! rc) && card && get_parameter (para, pAUTHKEYTYPE))
2579
 
    {
2580
 
      rc = gen_card_key (PUBKEY_ALGO_RSA, 3, pub_root, sec_root,
2581
 
                         get_parameter_u32 (para, pKEYEXPIRE), para);
2582
 
 
2583
 
      if (!rc)
2584
 
        rc = write_keybinding (pub_root, pub_root, sk, PUBKEY_USAGE_AUTH);
2585
 
      if (!rc)
2586
 
        rc = write_keybinding (sec_root, pub_root, sk, PUBKEY_USAGE_AUTH);
2587
 
    }
2588
 
 
2589
 
 
2590
 
  if (!rc && outctrl->use_files)
2591
 
    {                           /* direct write to specified files */
2592
 
      rc = write_keyblock (outctrl->pub.stream, pub_root);
2593
 
      if (rc)
2594
 
        log_error ("can't write public key: %s\n", gpg_strerror (rc));
2595
 
      if (!rc)
2596
 
        {
2597
 
          rc = write_keyblock (outctrl->sec.stream, sec_root);
2598
 
          if (rc)
2599
 
            log_error ("can't write secret key: %s\n", gpg_strerror (rc));
2600
 
        }
2601
 
 
2602
 
    }
2603
 
  else if (!rc)
2604
 
    {                           /* write to the standard keyrings */
2605
 
      KEYDB_HANDLE pub_hd = keydb_new (0);
2606
 
      KEYDB_HANDLE sec_hd = keydb_new (1);
2607
 
 
2608
 
      /* FIXME: we may have to create the keyring first */
2609
 
      rc = keydb_locate_writable (pub_hd, NULL);
2610
 
      if (rc)
2611
 
        log_error (_("no writable public keyring found: %s\n"),
2612
 
                   gpg_strerror (rc));
2613
 
 
2614
 
      if (!rc)
2615
 
        {
2616
 
          rc = keydb_locate_writable (sec_hd, NULL);
2617
 
          if (rc)
2618
 
            log_error (_("no writable secret keyring found: %s\n"),
2619
 
                       gpg_strerror (rc));
2620
 
        }
2621
 
 
2622
 
      if (!rc && opt.verbose)
2623
 
        {
2624
 
          log_info (_("writing public key to `%s'\n"),
2625
 
                    keydb_get_resource_name (pub_hd));
2626
 
          if (card)
2627
 
            log_info (_("writing secret key stub to `%s'\n"),
2628
 
                      keydb_get_resource_name (sec_hd));
2629
 
          else
2630
 
            log_info (_("writing secret key to `%s'\n"),
2631
 
                      keydb_get_resource_name (sec_hd));
2632
 
        }
2633
 
 
2634
 
      if (!rc)
2635
 
        {
2636
 
          rc = keydb_insert_keyblock (pub_hd, pub_root);
2637
 
          if (rc)
2638
 
            log_error (_("error writing public keyring `%s': %s\n"),
2639
 
                       keydb_get_resource_name (pub_hd), gpg_strerror (rc));
2640
 
        }
2641
 
 
2642
 
      if (!rc)
2643
 
        {
2644
 
          rc = keydb_insert_keyblock (sec_hd, sec_root);
2645
 
          if (rc)
2646
 
            log_error (_("error writing secret keyring `%s': %s\n"),
2647
 
                       keydb_get_resource_name (pub_hd), gpg_strerror (rc));
2648
 
        }
2649
 
 
2650
 
      keydb_release (pub_hd);
2651
 
      keydb_release (sec_hd);
2652
 
 
2653
 
      if (!rc)
2654
 
        {
2655
 
          int no_enc_rsa =
2656
 
            get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_RSA
2657
 
            && get_parameter_uint (para, pKEYUSAGE)
2658
 
            && !(get_parameter_uint (para, pKEYUSAGE) & PUBKEY_USAGE_ENC);
2659
 
          PKT_public_key *pk = find_kbnode (pub_root,
2660
 
                                            PKT_PUBLIC_KEY)->pkt->pkt.
2661
 
            public_key;
2662
 
 
2663
 
          update_ownertrust (pk,
2664
 
                             ((get_ownertrust (pk) & ~TRUST_MASK)
2665
 
                              | TRUST_ULTIMATE));
2666
 
 
2667
 
          if (!opt.batch)
2668
 
            {
2669
 
              tty_printf (_("public and secret key created and signed.\n"));
2670
 
              tty_printf (_("key marked as ultimately trusted.\n"));
2671
 
              tty_printf ("\n");
2672
 
              list_keyblock (pub_root, 0, 1, NULL);
2673
 
            }
2674
 
 
2675
 
 
2676
 
          if (!opt.batch
2677
 
              && (get_parameter_algo (para, pKEYTYPE) == PUBKEY_ALGO_DSA
2678
 
                  || no_enc_rsa) && !get_parameter (para, pSUBKEYTYPE))
2679
 
            {
2680
 
              tty_printf (_("Note that this key cannot be used for "
2681
 
                            "encryption.  You may want to use\n"
2682
 
                            "the command \"--edit-key\" to generate a "
2683
 
                            "secondary key for this purpose.\n"));
2684
 
            }
2685
 
 
2686
 
          if (!opt.batch && card)
2687
 
            {
2688
 
              tty_printf(_(
2689
 
"Please create a revocation certificate now, so that you are able\n"
2690
 
"to revoke the key if it ever happens that you lose your card or\n"
2691
 
"the card gets damaged.  Use the command \"--gen-revoke\".\n"
2692
 
                         ));
2693
 
            }
2694
 
        }
2695
 
    }
2696
 
 
2697
 
  if (rc)
2698
 
    {
2699
 
      if (opt.batch)
2700
 
        log_error ("key generation failed: %s\n", gpg_strerror (rc));
2701
 
      else
2702
 
        tty_printf (_("Key generation failed: %s\n"), gpg_strerror (rc));
2703
 
    }
2704
 
  else
2705
 
    {
2706
 
      PKT_public_key *pk = find_kbnode (pub_root,
2707
 
                                        PKT_PUBLIC_KEY)->pkt->pkt.public_key;
2708
 
      print_status_key_created (did_sub ? 'B' : 'P', pk);
2709
 
    }
2710
 
 
2711
 
  release_kbnode (pub_root);
2712
 
  release_kbnode (sec_root);
2713
 
  if (sk && !card)         /* The unprotected secret key unless we have */
2714
 
    free_secret_key (sk);  /* a shallow copy in card mode. */
 
2862
  int i;
 
2863
  size_t nskey, npkey;
 
2864
 
 
2865
  npkey = pubkey_get_npkey (algo);
 
2866
  nskey = pubkey_get_nskey (algo);
 
2867
  assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
 
2868
 
 
2869
  if (nbits < 512)
 
2870
    {
 
2871
      nbits = 512;
 
2872
      log_info (_("keysize invalid; using %u bits\n"), nbits );
 
2873
    }
 
2874
 
 
2875
  if ((nbits % 32)) 
 
2876
    {
 
2877
      nbits = ((nbits + 31) / 32) * 32;
 
2878
      log_info(_("keysize rounded up to %u bits\n"), nbits );
 
2879
    }
 
2880
 
 
2881
  dek = do_ask_passphrase (&s2k);
 
2882
 
 
2883
  sk = xmalloc_clear (sizeof *sk);
 
2884
  sk->timestamp = created_at;
 
2885
  sk->version = 4;
 
2886
  sk->pubkey_algo = algo;
 
2887
 
 
2888
  if ( !is_RSA (algo) )
 
2889
    {
 
2890
      log_error ("only RSA is supported for offline generated keys\n");
 
2891
      rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 
2892
      goto leave;
 
2893
    }
 
2894
  rc = gcry_sexp_build (&s_parms, NULL,
 
2895
                        "(genkey(rsa(nbits %d)))",
 
2896
                        (int)nbits);
 
2897
  if (rc)
 
2898
    log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
 
2899
  rc = gcry_pk_genkey (&s_key, s_parms);
 
2900
  gcry_sexp_release (s_parms);
 
2901
  if (rc)
 
2902
    {
 
2903
      log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
 
2904
      goto leave;
 
2905
    }
 
2906
  rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
 
2907
  gcry_sexp_release (s_key);
 
2908
  if (rc) 
 
2909
    {
 
2910
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
 
2911
      goto leave;
 
2912
    }
 
2913
  
 
2914
  for (i=npkey; i < nskey; i++)
 
2915
    sk->csum += checksum_mpi (sk->skey[i]);
 
2916
 
 
2917
  if (r_sk_unprotected) 
 
2918
    *r_sk_unprotected = copy_secret_key (NULL, sk);
 
2919
 
 
2920
  rc = genhelp_protect (dek, s2k, sk);
 
2921
  if (rc)
 
2922
    goto leave;
 
2923
 
 
2924
  if (r_sk_protected)
 
2925
    {
 
2926
      *r_sk_protected = sk;
 
2927
      sk = NULL;
 
2928
    }
 
2929
 
 
2930
 leave:
 
2931
  if (sk)
 
2932
    free_secret_key (sk);
 
2933
  xfree (dek);
 
2934
  xfree (s2k);
 
2935
  return rc;
 
2936
}
 
2937
#endif /* ENABLE_CARD_SUPPORT */
 
2938
 
 
2939
/* Create and delete a dummy packet to start off a list of kbnodes. */
 
2940
static void
 
2941
start_tree(KBNODE *tree)
 
2942
{
 
2943
  PACKET *pkt;
 
2944
 
 
2945
  pkt=xmalloc_clear(sizeof(*pkt));
 
2946
  pkt->pkttype=PKT_NONE;
 
2947
  *tree=new_kbnode(pkt);
 
2948
  delete_kbnode(*tree);
 
2949
}
 
2950
 
 
2951
static void
 
2952
do_generate_keypair( struct para_data_s *para,
 
2953
                     struct output_control_s *outctrl, int card )
 
2954
{
 
2955
    KBNODE pub_root = NULL;
 
2956
    KBNODE sec_root = NULL;
 
2957
    PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
 
2958
    const char *s;
 
2959
    struct revocation_key *revkey;
 
2960
    int rc;
 
2961
    int did_sub = 0;
 
2962
 
 
2963
    if( outctrl->dryrun )
 
2964
      {
 
2965
        log_info("dry-run mode - key generation skipped\n");
 
2966
        return;
 
2967
      }
 
2968
 
 
2969
    if( outctrl->use_files ) {
 
2970
        if( outctrl->pub.newfname ) {
 
2971
            iobuf_close(outctrl->pub.stream);
 
2972
            outctrl->pub.stream = NULL;
 
2973
            if (outctrl->pub.fname)
 
2974
              iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
 
2975
            xfree( outctrl->pub.fname );
 
2976
            outctrl->pub.fname =  outctrl->pub.newfname;
 
2977
            outctrl->pub.newfname = NULL;
 
2978
 
 
2979
            if (is_secured_filename (outctrl->pub.fname) ) {
 
2980
                outctrl->pub.stream = NULL;
 
2981
                errno = EPERM;
 
2982
            }
 
2983
            else
 
2984
                outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
 
2985
            if( !outctrl->pub.stream ) {
 
2986
                log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
 
2987
                                                     strerror(errno) );
 
2988
                return;
 
2989
            }
 
2990
            if( opt.armor ) {
 
2991
                outctrl->pub.afx.what = 1;
 
2992
                iobuf_push_filter( outctrl->pub.stream, armor_filter,
 
2993
                                                    &outctrl->pub.afx );
 
2994
            }
 
2995
        }
 
2996
        if( outctrl->sec.newfname ) {
 
2997
            mode_t oldmask;
 
2998
 
 
2999
            iobuf_close(outctrl->sec.stream);
 
3000
            outctrl->sec.stream = NULL;
 
3001
            if (outctrl->sec.fname)
 
3002
              iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
 
3003
            xfree( outctrl->sec.fname );
 
3004
            outctrl->sec.fname =  outctrl->sec.newfname;
 
3005
            outctrl->sec.newfname = NULL;
 
3006
 
 
3007
            oldmask = umask (077);
 
3008
            if (is_secured_filename (outctrl->sec.fname) ) {
 
3009
                outctrl->sec.stream = NULL;
 
3010
                errno = EPERM;
 
3011
            }
 
3012
            else
 
3013
                outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
 
3014
            umask (oldmask);
 
3015
            if( !outctrl->sec.stream ) {
 
3016
                log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
 
3017
                                                     strerror(errno) );
 
3018
                return;
 
3019
            }
 
3020
            if( opt.armor ) {
 
3021
                outctrl->sec.afx.what = 5;
 
3022
                iobuf_push_filter( outctrl->sec.stream, armor_filter,
 
3023
                                                    &outctrl->sec.afx );
 
3024
            }
 
3025
        }
 
3026
        assert( outctrl->pub.stream );
 
3027
        assert( outctrl->sec.stream );
 
3028
        if( opt.verbose ) {
 
3029
            log_info(_("writing public key to `%s'\n"), outctrl->pub.fname );
 
3030
            if (card)
 
3031
              log_info (_("writing secret key stub to `%s'\n"),
 
3032
                        outctrl->sec.fname);
 
3033
            else
 
3034
              log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
 
3035
        }
 
3036
    }
 
3037
 
 
3038
 
 
3039
    /* we create the packets as a tree of kbnodes. Because the
 
3040
     * structure we create is known in advance we simply generate a
 
3041
     * linked list.  The first packet is a dummy packet which we flag
 
3042
     * as deleted.  The very first packet must always be a KEY packet.
 
3043
     */
 
3044
    
 
3045
    start_tree(&pub_root);
 
3046
    start_tree(&sec_root);
 
3047
 
 
3048
    if (!card)
 
3049
      {
 
3050
        rc = do_create( get_parameter_algo( para, pKEYTYPE ),
 
3051
                        get_parameter_uint( para, pKEYLENGTH ),
 
3052
                        pub_root, sec_root,
 
3053
                        get_parameter_dek( para, pPASSPHRASE_DEK ),
 
3054
                        get_parameter_s2k( para, pPASSPHRASE_S2K ),
 
3055
                        &pri_sk,
 
3056
                        get_parameter_u32( para, pKEYEXPIRE ), 0 );
 
3057
      }
 
3058
    else
 
3059
      {
 
3060
        rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root,
 
3061
                           get_parameter_u32 (para, pKEYEXPIRE), para);
 
3062
        if (!rc)
 
3063
          {
 
3064
            pri_sk = sec_root->next->pkt->pkt.secret_key;
 
3065
            assert (pri_sk);
 
3066
          }
 
3067
      }
 
3068
 
 
3069
    if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
 
3070
      {
 
3071
        rc=write_direct_sig(pub_root,pub_root,pri_sk,revkey);
 
3072
        if(!rc)
 
3073
          write_direct_sig(sec_root,pub_root,pri_sk,revkey);
 
3074
      }
 
3075
 
 
3076
    if( !rc && (s=get_parameter_value(para, pUSERID)) )
 
3077
      {
 
3078
        write_uid(pub_root, s );
 
3079
        if( !rc )
 
3080
          write_uid(sec_root, s );
 
3081
 
 
3082
        if( !rc )
 
3083
          rc = write_selfsigs(sec_root, pub_root, pri_sk,
 
3084
                              get_parameter_uint (para, pKEYUSAGE));
 
3085
      }
 
3086
 
 
3087
    /* Write the auth key to the card before the encryption key.  This
 
3088
       is a partial workaround for a PGP bug (as of this writing, all
 
3089
       versions including 8.1), that causes it to try and encrypt to
 
3090
       the most recent subkey regardless of whether that subkey is
 
3091
       actually an encryption type.  In this case, the auth key is an
 
3092
       RSA key so it succeeds. */
 
3093
 
 
3094
    if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
 
3095
      {
 
3096
        rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root,
 
3097
                           get_parameter_u32 (para, pKEYEXPIRE), para);
 
3098
        
 
3099
        if (!rc)
 
3100
          rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk, PUBKEY_USAGE_AUTH);
 
3101
        if (!rc)
 
3102
          rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk, PUBKEY_USAGE_AUTH);
 
3103
      }
 
3104
 
 
3105
    if( !rc && get_parameter( para, pSUBKEYTYPE ) )
 
3106
      {
 
3107
        if (!card)
 
3108
          {
 
3109
            rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
 
3110
                            get_parameter_uint( para, pSUBKEYLENGTH ),
 
3111
                            pub_root, sec_root,
 
3112
                            get_parameter_dek( para, pPASSPHRASE_DEK ),
 
3113
                            get_parameter_s2k( para, pPASSPHRASE_S2K ),
 
3114
                            &sub_sk,
 
3115
                            get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
 
3116
          }
 
3117
        else
 
3118
          {
 
3119
            if ((s = get_parameter_value (para, pBACKUPENCDIR)))
 
3120
              {
 
3121
                /* A backup of the encryption key has been requested.
 
3122
                   Generate the key i software and import it then to
 
3123
                   the card.  Write a backup file. */
 
3124
                rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
 
3125
                                               pub_root, sec_root,
 
3126
                                               get_parameter_u32 (para,
 
3127
                                                                  pKEYEXPIRE),
 
3128
                                               para, s);
 
3129
              }
 
3130
            else
 
3131
              rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
 
3132
                                 get_parameter_u32 (para, pKEYEXPIRE), para);
 
3133
          }
 
3134
 
 
3135
        if( !rc )
 
3136
          rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
 
3137
                                get_parameter_uint (para, pSUBKEYUSAGE));
 
3138
        if( !rc )
 
3139
          rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
 
3140
                                get_parameter_uint (para, pSUBKEYUSAGE));
 
3141
        did_sub = 1;
 
3142
      }
 
3143
 
 
3144
    if( !rc && outctrl->use_files ) { /* direct write to specified files */
 
3145
        rc = write_keyblock( outctrl->pub.stream, pub_root );
 
3146
        if( rc )
 
3147
            log_error("can't write public key: %s\n", g10_errstr(rc) );
 
3148
        if( !rc ) {
 
3149
            rc = write_keyblock( outctrl->sec.stream, sec_root );
 
3150
            if( rc )
 
3151
                log_error("can't write secret key: %s\n", g10_errstr(rc) );
 
3152
        }
 
3153
 
 
3154
    }
 
3155
    else if( !rc ) { /* write to the standard keyrings */
 
3156
        KEYDB_HANDLE pub_hd = keydb_new (0);
 
3157
        KEYDB_HANDLE sec_hd = keydb_new (1);
 
3158
 
 
3159
        /* FIXME: we may have to create the keyring first */
 
3160
        rc = keydb_locate_writable (pub_hd, NULL);
 
3161
        if (rc) 
 
3162
            log_error (_("no writable public keyring found: %s\n"),
 
3163
                       g10_errstr (rc));
 
3164
 
 
3165
        if (!rc) {  
 
3166
            rc = keydb_locate_writable (sec_hd, NULL);
 
3167
            if (rc) 
 
3168
                log_error (_("no writable secret keyring found: %s\n"),
 
3169
                           g10_errstr (rc));
 
3170
        }
 
3171
 
 
3172
        if (!rc && opt.verbose) {
 
3173
            log_info(_("writing public key to `%s'\n"),
 
3174
                     keydb_get_resource_name (pub_hd));
 
3175
            if (card)
 
3176
              log_info (_("writing secret key stub to `%s'\n"),
 
3177
                        keydb_get_resource_name (sec_hd));
 
3178
            else
 
3179
              log_info(_("writing secret key to `%s'\n"),
 
3180
                       keydb_get_resource_name (sec_hd));
 
3181
        }
 
3182
 
 
3183
        if (!rc) {
 
3184
            rc = keydb_insert_keyblock (pub_hd, pub_root);
 
3185
            if (rc)
 
3186
                log_error (_("error writing public keyring `%s': %s\n"),
 
3187
                           keydb_get_resource_name (pub_hd), g10_errstr(rc));
 
3188
        }
 
3189
 
 
3190
        if (!rc) {
 
3191
            rc = keydb_insert_keyblock (sec_hd, sec_root);
 
3192
            if (rc)
 
3193
                log_error (_("error writing secret keyring `%s': %s\n"),
 
3194
                           keydb_get_resource_name (pub_hd), g10_errstr(rc));
 
3195
        }
 
3196
 
 
3197
        keydb_release (pub_hd);
 
3198
        keydb_release (sec_hd);
 
3199
 
 
3200
        if (!rc) {
 
3201
            int no_enc_rsa =
 
3202
                get_parameter_algo(para, pKEYTYPE) == PUBKEY_ALGO_RSA
 
3203
                && get_parameter_uint( para, pKEYUSAGE )
 
3204
                && !(get_parameter_uint( para,pKEYUSAGE) & PUBKEY_USAGE_ENC);
 
3205
            PKT_public_key *pk = find_kbnode (pub_root, 
 
3206
                                    PKT_PUBLIC_KEY)->pkt->pkt.public_key;
 
3207
 
 
3208
            keyid_from_pk(pk,pk->main_keyid);
 
3209
            register_trusted_keyid(pk->main_keyid);
 
3210
 
 
3211
            update_ownertrust (pk,
 
3212
                               ((get_ownertrust (pk) & ~TRUST_MASK)
 
3213
                                | TRUST_ULTIMATE ));
 
3214
 
 
3215
            if (!opt.batch) {
 
3216
                tty_printf(_("public and secret key created and signed.\n") );
 
3217
                tty_printf("\n");
 
3218
                list_keyblock(pub_root,0,1,NULL);
 
3219
            }
 
3220
            
 
3221
 
 
3222
            if( !opt.batch
 
3223
                && ( get_parameter_algo( para, pKEYTYPE ) == PUBKEY_ALGO_DSA
 
3224
                     || no_enc_rsa )
 
3225
                && !get_parameter( para, pSUBKEYTYPE ) )
 
3226
            {
 
3227
                tty_printf(_("Note that this key cannot be used for "
 
3228
                             "encryption.  You may want to use\n"
 
3229
                             "the command \"--edit-key\" to generate a "
 
3230
                             "subkey for this purpose.\n") );
 
3231
            }
 
3232
        }
 
3233
    }
 
3234
 
 
3235
    if( rc ) {
 
3236
        if( opt.batch )
 
3237
            log_error("key generation failed: %s\n", g10_errstr(rc) );
 
3238
        else
 
3239
            tty_printf(_("Key generation failed: %s\n"), g10_errstr(rc) );
 
3240
        print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
 
3241
    }
 
3242
    else {
 
3243
        PKT_public_key *pk = find_kbnode (pub_root, 
 
3244
                                    PKT_PUBLIC_KEY)->pkt->pkt.public_key;
 
3245
        print_status_key_created (did_sub? 'B':'P', pk,
 
3246
                                  get_parameter_value (para, pHANDLE));
 
3247
    }
 
3248
    release_kbnode( pub_root );
 
3249
    release_kbnode( sec_root );
 
3250
 
 
3251
    if( pri_sk && !card) /* the unprotected  secret key unless we have a */
 
3252
      free_secret_key(pri_sk); /* shallow copy in card mode. */
 
3253
    if( sub_sk )
 
3254
        free_secret_key(sub_sk);
2715
3255
}
2716
3256
 
2717
3257
 
2724
3264
{
2725
3265
    int okay=0, rc=0;
2726
3266
    KBNODE node;
2727
 
    PKT_secret_key *sk = NULL; /* this is the primary sk */
 
3267
    PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
2728
3268
    int algo;
2729
3269
    unsigned int use;
2730
3270
    u32 expire;
2733
3273
    DEK *dek = NULL;
2734
3274
    STRING2KEY *s2k = NULL;
2735
3275
    u32 cur_time;
 
3276
    int ask_pass = 0;
2736
3277
 
2737
3278
    /* break out the primary secret key */
2738
3279
    node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
2742
3283
    }
2743
3284
 
2744
3285
    /* make a copy of the sk to keep the protected one in the keyblock */
2745
 
    sk = copy_secret_key( NULL, node->pkt->pkt.secret_key );
 
3286
    pri_sk = copy_secret_key( NULL, node->pkt->pkt.secret_key );
2746
3287
 
2747
3288
    cur_time = make_timestamp();
2748
 
    if( sk->timestamp > cur_time ) {
2749
 
        ulong d = sk->timestamp - cur_time;
 
3289
    if( pri_sk->timestamp > cur_time ) {
 
3290
        ulong d = pri_sk->timestamp - cur_time;
2750
3291
        log_info( d==1 ? _("key has been created %lu second "
2751
3292
                           "in future (time warp or clock problem)\n")
2752
3293
                       : _("key has been created %lu seconds "
2753
3294
                           "in future (time warp or clock problem)\n"), d );
2754
3295
        if( !opt.ignore_time_conflict ) {
2755
 
            rc = GPG_ERR_TIME_CONFLICT;
 
3296
            rc = G10ERR_TIME_CONFLICT;
2756
3297
            goto leave;
2757
3298
        }
2758
3299
    }
2759
3300
 
2760
 
    if (sk->version < 4) {
 
3301
    if (pri_sk->version < 4) {
2761
3302
        log_info (_("NOTE: creating subkeys for v3 keys "
2762
3303
                    "is not OpenPGP compliant\n"));
2763
3304
        goto leave;
2764
3305
    }
2765
3306
 
2766
 
    /* unprotect to get the passphrase */
2767
 
    switch( is_secret_key_protected( sk ) ) {
 
3307
    if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001) {
 
3308
        tty_printf(_("Secret parts of primary key are not available.\n"));
 
3309
        rc = G10ERR_NO_SECKEY;
 
3310
        goto leave;
 
3311
    }
 
3312
 
 
3313
 
 
3314
    /* Unprotect to get the passphrase.  */
 
3315
    switch( is_secret_key_protected( pri_sk ) ) {
2768
3316
      case -1:
2769
 
        rc = GPG_ERR_PUBKEY_ALGO;
 
3317
        rc = G10ERR_PUBKEY_ALGO;
2770
3318
        break;
2771
3319
      case 0:
2772
 
        tty_printf("This key is not protected.\n");
 
3320
        tty_printf(_("This key is not protected.\n"));
2773
3321
        break;
 
3322
      case -2:
 
3323
        tty_printf(_("Secret parts of primary key are stored on-card.\n"));
 
3324
        ask_pass = 1;
 
3325
        break;
2774
3326
      default:
2775
 
        tty_printf("Key is protected.\n");
2776
 
        rc = check_secret_key( sk, 0 );
2777
 
        if( !rc )
2778
 
            passphrase = get_last_passphrase();
2779
 
        break;
 
3327
        tty_printf(_("Key is protected.\n"));
 
3328
        rc = check_secret_key( pri_sk, 0 );
 
3329
        if( !rc )
 
3330
            passphrase = get_last_passphrase();
 
3331
        break;
2780
3332
    }
2781
3333
    if( rc )
2782
3334
        goto leave;
2783
3335
 
2784
 
 
2785
3336
    algo = ask_algo( 1, &use );
2786
3337
    assert(algo);
2787
3338
    nbits = ask_keysize( algo );
2788
 
    expire = ask_expire_interval(0);
 
3339
    expire = ask_expire_interval(0,NULL);
2789
3340
    if( !cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
2790
 
                                                  _("Really create? ") ) )
 
3341
                                                  _("Really create? (y/N) ")))
2791
3342
        goto leave;
2792
3343
 
2793
 
    if( passphrase ) {
2794
 
        s2k = xmalloc_secure ( sizeof *s2k );
 
3344
    if (ask_pass)
 
3345
        dek = do_ask_passphrase (&s2k);
 
3346
    else if (passphrase) {
 
3347
        s2k = xmalloc_secure( sizeof *s2k );
2795
3348
        s2k->mode = opt.s2k_mode;
2796
 
        s2k->hash_algo = opt.s2k_digest_algo;
 
3349
        s2k->hash_algo = S2K_DIGEST_ALGO;
2797
3350
        set_next_passphrase( passphrase );
2798
3351
        dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2799
3352
                                 NULL, NULL );
2800
3353
    }
2801
3354
 
2802
3355
    rc = do_create( algo, nbits, pub_keyblock, sec_keyblock,
2803
 
                                      dek, s2k, NULL, expire );
2804
 
    if( !rc )
2805
 
        rc = write_keybinding(pub_keyblock, pub_keyblock, sk, use);
2806
 
    if( !rc )
2807
 
        rc = write_keybinding(sec_keyblock, pub_keyblock, sk, use);
 
3356
                                      dek, s2k, &sub_sk, expire, 1 );
 
3357
    if( !rc )
 
3358
        rc = write_keybinding(pub_keyblock, pub_keyblock, pri_sk, sub_sk, use);
 
3359
    if( !rc )
 
3360
        rc = write_keybinding(sec_keyblock, pub_keyblock, pri_sk, sub_sk, use);
2808
3361
    if( !rc ) {
2809
3362
        okay = 1;
2810
3363
        write_status_text (STATUS_KEY_CREATED, "S");
2812
3365
 
2813
3366
  leave:
2814
3367
    if( rc )
2815
 
        log_error(_("Key generation failed: %s\n"), gpg_strerror (rc) );
2816
 
    xfree ( passphrase );
2817
 
    xfree ( dek );
2818
 
    xfree ( s2k );
2819
 
    if( sk ) /* release the copy of the (now unprotected) secret key */
2820
 
        free_secret_key(sk);
 
3368
        log_error(_("Key generation failed: %s\n"), g10_errstr(rc) );
 
3369
    xfree( passphrase );
 
3370
    xfree( dek );
 
3371
    xfree( s2k );
 
3372
    /* release the copy of the (now unprotected) secret keys */
 
3373
    if( pri_sk )
 
3374
        free_secret_key(pri_sk);
 
3375
    if( sub_sk )
 
3376
        free_secret_key(sub_sk);
2821
3377
    set_next_passphrase( NULL );
2822
3378
    return okay;
2823
3379
}
2824
3380
 
 
3381
 
 
3382
#ifdef ENABLE_CARD_SUPPORT
 
3383
/* Generate a subkey on a card. */
 
3384
int
 
3385
generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
 
3386
                          int keyno, const char *serialno)
 
3387
{
 
3388
  int okay=0, rc=0;
 
3389
  KBNODE node;
 
3390
  PKT_secret_key *pri_sk = NULL;
 
3391
  int algo;
 
3392
  unsigned int use;
 
3393
  u32 expire;
 
3394
  char *passphrase = NULL;
 
3395
  u32 cur_time;
 
3396
  struct para_data_s *para = NULL;
 
3397
 
 
3398
  assert (keyno >= 1 && keyno <= 3);
 
3399
 
 
3400
  para = xcalloc (1, sizeof *para + strlen (serialno) );
 
3401
  para->key = pSERIALNO;
 
3402
  strcpy (para->u.value, serialno);
 
3403
 
 
3404
  /* Break out the primary secret key */
 
3405
  node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
 
3406
  if(!node)
 
3407
    {
 
3408
      log_error("Oops; secret key not found anymore!\n");
 
3409
      goto leave;
 
3410
    }
 
3411
 
 
3412
  /* Make a copy of the sk to keep the protected one in the keyblock */
 
3413
  pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
 
3414
 
 
3415
  cur_time = make_timestamp();
 
3416
  if (pri_sk->timestamp > cur_time)
 
3417
    {
 
3418
      ulong d = pri_sk->timestamp - cur_time;
 
3419
      log_info (d==1 ? _("key has been created %lu second "
 
3420
                         "in future (time warp or clock problem)\n")
 
3421
                     : _("key has been created %lu seconds "
 
3422
                         "in future (time warp or clock problem)\n"), d );
 
3423
        if (!opt.ignore_time_conflict)
 
3424
          {
 
3425
            rc = G10ERR_TIME_CONFLICT;
 
3426
            goto leave;
 
3427
          }
 
3428
    }
 
3429
 
 
3430
  if (pri_sk->version < 4)
 
3431
    {
 
3432
      log_info (_("NOTE: creating subkeys for v3 keys "
 
3433
                  "is not OpenPGP compliant\n"));
 
3434
      goto leave;
 
3435
    }
 
3436
 
 
3437
  /* Unprotect to get the passphrase. */
 
3438
  switch( is_secret_key_protected (pri_sk) )
 
3439
    {
 
3440
    case -1:
 
3441
      rc = G10ERR_PUBKEY_ALGO;
 
3442
      break;
 
3443
    case 0:
 
3444
      tty_printf("This key is not protected.\n");
 
3445
      break;
 
3446
    default:
 
3447
      tty_printf("Key is protected.\n");
 
3448
      rc = check_secret_key( pri_sk, 0 );
 
3449
      if (!rc)
 
3450
        passphrase = get_last_passphrase();
 
3451
      break;
 
3452
    }
 
3453
  if (rc)
 
3454
    goto leave;
 
3455
 
 
3456
  algo = PUBKEY_ALGO_RSA;
 
3457
  expire = ask_expire_interval (0,NULL);
 
3458
  if (keyno == 1)
 
3459
    use = PUBKEY_USAGE_SIG;
 
3460
  else if (keyno == 2)
 
3461
    use = PUBKEY_USAGE_ENC;
 
3462
  else
 
3463
    use = PUBKEY_USAGE_AUTH;
 
3464
  if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
 
3465
                                               _("Really create? (y/N) ")))
 
3466
    goto leave;
 
3467
 
 
3468
  if (passphrase)
 
3469
    set_next_passphrase (passphrase);
 
3470
  rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock, expire, para);
 
3471
  if (!rc)
 
3472
    rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, NULL, use);
 
3473
  if (!rc)
 
3474
    rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, NULL, use);
 
3475
  if (!rc)
 
3476
    {
 
3477
      okay = 1;
 
3478
      write_status_text (STATUS_KEY_CREATED, "S");
 
3479
    }
 
3480
 
 
3481
 leave:
 
3482
  if (rc)
 
3483
    log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
 
3484
  xfree (passphrase);
 
3485
  /* Release the copy of the (now unprotected) secret keys. */
 
3486
  if (pri_sk)
 
3487
    free_secret_key (pri_sk);
 
3488
  set_next_passphrase( NULL );
 
3489
  release_parameter_list (para);
 
3490
  return okay;
 
3491
}
 
3492
#endif /* !ENABLE_CARD_SUPPORT */
 
3493
 
 
3494
 
2825
3495
/****************
2826
3496
 * Write a keyblock to an output stream
2827
3497
 */
2828
3498
static int
2829
 
write_keyblock( iobuf_t out, KBNODE node )
 
3499
write_keyblock( IOBUF out, KBNODE node )
2830
3500
{
2831
 
    for( ; node ; node = node->next ) {
2832
 
        int rc = build_packet( out, node->pkt );
2833
 
        if( rc ) {
2834
 
            log_error("build_packet(%d) failed: %s\n",
2835
 
                        node->pkt->pkttype, gpg_strerror (rc) );
2836
 
            return rc;
 
3501
  for( ; node ; node = node->next )
 
3502
    {
 
3503
      if(!is_deleted_kbnode(node))
 
3504
        {
 
3505
          int rc = build_packet( out, node->pkt );
 
3506
          if( rc )
 
3507
            {
 
3508
              log_error("build_packet(%d) failed: %s\n",
 
3509
                        node->pkt->pkttype, g10_errstr(rc) );
 
3510
              return rc;
 
3511
            }
2837
3512
        }
2838
3513
    }
2839
 
    return 0;
 
3514
 
 
3515
  return 0;
2840
3516
}
2841
3517
 
2842
 
 
2843
3518
 
2844
3519
static int
2845
 
gen_card_key (int algo, int keyno, KBNODE pub_root, KBNODE sec_root,
 
3520
gen_card_key (int algo, int keyno, int is_primary,
 
3521
              KBNODE pub_root, KBNODE sec_root,
2846
3522
              u32 expireval, struct para_data_s *para)
2847
3523
{
 
3524
#ifdef ENABLE_CARD_SUPPORT
2848
3525
  int rc;
2849
3526
  const char *s;
2850
3527
  struct agent_card_genkey_s info;
2853
3530
  PKT_public_key *pk;
2854
3531
 
2855
3532
  assert (algo == PUBKEY_ALGO_RSA);
2856
 
 
2857
 
  rc = agent_scd_genkey (&info, keyno, 1);
 
3533
  
 
3534
  /* Fixme: We don't have the serialnumber available, thus passing NULL. */
 
3535
  rc = agent_scd_genkey (&info, keyno, 1, NULL);
2858
3536
/*    if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
2859
3537
/*      { */
2860
3538
/*        tty_printf ("\n"); */
2866
3544
/*      } */
2867
3545
 
2868
3546
  if (rc)
2869
 
    return rc;
2870
 
 
 
3547
    {
 
3548
      log_error ("key generation failed: %s\n", gpg_strerror (rc));
 
3549
      return rc;
 
3550
    }
2871
3551
  if ( !info.n || !info.e )
2872
3552
    {
2873
3553
      log_error ("communication error with SCD\n");
2874
 
      gcry_mpi_release (info.n);
2875
 
      gcry_mpi_release (info.e);
 
3554
      mpi_free (info.n);
 
3555
      mpi_free (info.e);
2876
3556
      return gpg_error (GPG_ERR_GENERAL);
2877
3557
    }
2878
3558
  
2900
3580
    }
2901
3581
 
2902
3582
  pkt = xcalloc (1,sizeof *pkt);
2903
 
  pkt->pkttype = keyno == 1 ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
2904
 
  pkt->pkt.public_key = pk;
2905
 
  add_kbnode(pub_root, new_kbnode( pkt ));
2906
 
 
2907
 
  pkt = xcalloc (1,sizeof *pkt);
2908
 
  pkt->pkttype = keyno == 1 ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
2909
 
  pkt->pkt.secret_key = sk;
2910
 
  add_kbnode(sec_root, new_kbnode( pkt ));
2911
 
 
2912
 
  return 0;
2913
 
}
2914
 
 
2915
 
 
2916
 
 
 
3583
  pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
 
3584
  pkt->pkt.public_key = pk;
 
3585
  add_kbnode(pub_root, new_kbnode( pkt ));
 
3586
 
 
3587
  pkt = xcalloc (1,sizeof *pkt);
 
3588
  pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
 
3589
  pkt->pkt.secret_key = sk;
 
3590
  add_kbnode(sec_root, new_kbnode( pkt ));
 
3591
 
 
3592
  return 0;
 
3593
#else
 
3594
  return -1;
 
3595
#endif /*!ENABLE_CARD_SUPPORT*/
 
3596
}
 
3597
 
 
3598
 
 
3599
 
 
3600
static int
 
3601
gen_card_key_with_backup (int algo, int keyno, int is_primary,
 
3602
                          KBNODE pub_root, KBNODE sec_root,
 
3603
                          u32 expireval, struct para_data_s *para,
 
3604
                          const char *backup_dir)
 
3605
{
 
3606
#ifdef ENABLE_CARD_SUPPORT
 
3607
  int rc;
 
3608
  const char *s;
 
3609
  PACKET *pkt;
 
3610
  PKT_secret_key *sk, *sk_unprotected, *sk_protected;
 
3611
  PKT_public_key *pk;
 
3612
  size_t n;
 
3613
  int i;
 
3614
 
 
3615
  rc = generate_raw_key (algo, 1024, make_timestamp (),
 
3616
                         &sk_unprotected, &sk_protected);
 
3617
  if (rc)
 
3618
    return rc;
 
3619
 
 
3620
  /* First, store the key to the card. */
 
3621
  rc = save_unprotected_key_to_card (sk_unprotected, keyno);
 
3622
  if (rc)
 
3623
    {
 
3624
      log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
 
3625
      free_secret_key (sk_unprotected);
 
3626
      free_secret_key (sk_protected);
 
3627
      return rc;
 
3628
    }
 
3629
 
 
3630
  /* Get rid of the secret key parameters and store the serial numer. */
 
3631
  sk = sk_unprotected;
 
3632
  n = pubkey_get_nskey (sk->pubkey_algo);
 
3633
  for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
 
3634
    {
 
3635
      mpi_free (sk->skey[i]);
 
3636
      sk->skey[i] = NULL;
 
3637
    }
 
3638
  i = pubkey_get_npkey (sk->pubkey_algo);
 
3639
  sk->skey[i] = mpi_set_opaque (NULL, xstrdup ("dummydata"), 10);
 
3640
  sk->is_protected = 1;
 
3641
  sk->protect.s2k.mode = 1002;
 
3642
  s = get_parameter_value (para, pSERIALNO);
 
3643
  assert (s);
 
3644
  for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
 
3645
       sk->protect.ivlen++, s += 2)
 
3646
    sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
 
3647
 
 
3648
  /* Now write the *protected* secret key to the file.  */
 
3649
  {
 
3650
    char name_buffer[50];
 
3651
    char *fname;
 
3652
    IOBUF fp;
 
3653
    mode_t oldmask;
 
3654
 
 
3655
    keyid_from_sk (sk, NULL);
 
3656
    sprintf (name_buffer,"sk_%08lX%08lX.gpg",
 
3657
             (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
 
3658
 
 
3659
    fname = make_filename (backup_dir, name_buffer, NULL);
 
3660
    oldmask = umask (077);
 
3661
    if (is_secured_filename (fname))
 
3662
      {
 
3663
        fp = NULL;
 
3664
        errno = EPERM;
 
3665
      }
 
3666
    else
 
3667
      fp = iobuf_create (fname);
 
3668
    umask (oldmask);
 
3669
    if (!fp) 
 
3670
      {
 
3671
        log_error (_("can't create backup file `%s': %s\n"),
 
3672
                   fname, strerror(errno) );
 
3673
        xfree (fname);
 
3674
        free_secret_key (sk_unprotected);
 
3675
        free_secret_key (sk_protected);
 
3676
        return G10ERR_OPEN_FILE;
 
3677
      }
 
3678
 
 
3679
    pkt = xcalloc (1, sizeof *pkt);
 
3680
    pkt->pkttype = PKT_SECRET_KEY;
 
3681
    pkt->pkt.secret_key = sk_protected;
 
3682
    sk_protected = NULL;
 
3683
 
 
3684
    rc = build_packet (fp, pkt);
 
3685
    if (rc)
 
3686
      {
 
3687
        log_error("build packet failed: %s\n", g10_errstr(rc) );
 
3688
        iobuf_cancel (fp);
 
3689
      }
 
3690
    else
 
3691
      {
 
3692
        byte array[MAX_FINGERPRINT_LEN];
 
3693
        char *fprbuf, *p;
 
3694
       
 
3695
        iobuf_close (fp);
 
3696
        iobuf_ioctl (NULL, 2, 0, (char*)fname);
 
3697
        log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
 
3698
 
 
3699
        fingerprint_from_sk (sk, array, &n);
 
3700
        p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
 
3701
        for (i=0; i < n ; i++, p += 2)
 
3702
          sprintf (p, "%02X", array[i]);
 
3703
        *p++ = ' ';
 
3704
        *p = 0;
 
3705
 
 
3706
        write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
 
3707
                                      fprbuf,
 
3708
                                      fname, strlen (fname),
 
3709
                                      0);
 
3710
        xfree (fprbuf);
 
3711
      }
 
3712
    free_packet (pkt);
 
3713
    xfree (pkt);
 
3714
    xfree (fname);
 
3715
    if (rc)
 
3716
      {
 
3717
        free_secret_key (sk_unprotected);
 
3718
        return rc;
 
3719
      }
 
3720
  }
 
3721
 
 
3722
  /* Create the public key from the secret key. */
 
3723
  pk = xcalloc (1, sizeof *pk );
 
3724
  pk->timestamp = sk->timestamp;
 
3725
  pk->version = sk->version;
 
3726
  if (expireval)
 
3727
      pk->expiredate = sk->expiredate = sk->timestamp + expireval;
 
3728
  pk->pubkey_algo = sk->pubkey_algo;
 
3729
  n = pubkey_get_npkey (sk->pubkey_algo);
 
3730
  for (i=0; i < n; i++)
 
3731
    pk->pkey[i] = mpi_copy (sk->skey[i]);
 
3732
 
 
3733
  /* Build packets and add them to the node lists.  */
 
3734
  pkt = xcalloc (1,sizeof *pkt);
 
3735
  pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
 
3736
  pkt->pkt.public_key = pk;
 
3737
  add_kbnode(pub_root, new_kbnode( pkt ));
 
3738
 
 
3739
  pkt = xcalloc (1,sizeof *pkt);
 
3740
  pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
 
3741
  pkt->pkt.secret_key = sk;
 
3742
  add_kbnode(sec_root, new_kbnode( pkt ));
 
3743
 
 
3744
  return 0;
 
3745
#else
 
3746
  return -1;
 
3747
#endif /*!ENABLE_CARD_SUPPORT*/
 
3748
}
 
3749
 
 
3750
 
 
3751
#ifdef ENABLE_CARD_SUPPORT
 
3752
int
 
3753
save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
 
3754
{
 
3755
  int rc;
 
3756
  unsigned char *rsa_n = NULL;
 
3757
  unsigned char *rsa_e = NULL;
 
3758
  unsigned char *rsa_p = NULL;
 
3759
  unsigned char *rsa_q = NULL;
 
3760
  unsigned int rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
 
3761
  unsigned char *sexp = NULL;
 
3762
  unsigned char *p;
 
3763
  char numbuf[55], numbuf2[50];
 
3764
 
 
3765
  assert (is_RSA (sk->pubkey_algo));
 
3766
  assert (!sk->is_protected);
 
3767
 
 
3768
  /* Copy the parameters into straight buffers. */
 
3769
  rsa_n = mpi_get_secure_buffer (sk->skey[0], &rsa_n_len, NULL);
 
3770
  rsa_e = mpi_get_secure_buffer (sk->skey[1], &rsa_e_len, NULL);
 
3771
  rsa_p = mpi_get_secure_buffer (sk->skey[3], &rsa_p_len, NULL);
 
3772
  rsa_q = mpi_get_secure_buffer (sk->skey[4], &rsa_q_len, NULL);
 
3773
  if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
 
3774
    {
 
3775
      rc = G10ERR_INV_ARG;
 
3776
      goto leave;
 
3777
    }
 
3778
 
 
3779
  /* Put the key into an S-expression. */
 
3780
  sexp = p = xmalloc_secure (30
 
3781
                             + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
 
3782
                             + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
 
3783
 
 
3784
  p = stpcpy (p,"(11:private-key(3:rsa(1:n");
 
3785
  sprintf (numbuf, "%u:", rsa_n_len);
 
3786
  p = stpcpy (p, numbuf);
 
3787
  memcpy (p, rsa_n, rsa_n_len);
 
3788
  p += rsa_n_len;
 
3789
 
 
3790
  sprintf (numbuf, ")(1:e%u:", rsa_e_len);
 
3791
  p = stpcpy (p, numbuf);
 
3792
  memcpy (p, rsa_e, rsa_e_len);
 
3793
  p += rsa_e_len;
 
3794
 
 
3795
  sprintf (numbuf, ")(1:p%u:", rsa_p_len);
 
3796
  p = stpcpy (p, numbuf);
 
3797
  memcpy (p, rsa_p, rsa_p_len);
 
3798
  p += rsa_p_len;
 
3799
 
 
3800
  sprintf (numbuf, ")(1:q%u:", rsa_q_len);
 
3801
  p = stpcpy (p, numbuf);
 
3802
  memcpy (p, rsa_q, rsa_q_len);
 
3803
  p += rsa_q_len;
 
3804
 
 
3805
  p = stpcpy (p,"))(10:created-at");
 
3806
  sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
 
3807
  sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
 
3808
  p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
 
3809
 
 
3810
  /* Fixme: Unfortunately we don't have the serialnumber available -
 
3811
     thus we can't pass it down to the agent. */ 
 
3812
  rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
 
3813
 
 
3814
 leave:
 
3815
  xfree (sexp);
 
3816
  xfree (rsa_n);
 
3817
  xfree (rsa_e);
 
3818
  xfree (rsa_p);
 
3819
  xfree (rsa_q);
 
3820
  return rc;
 
3821
}
 
3822
#endif /*ENABLE_CARD_SUPPORT*/