~ubuntu-branches/ubuntu/jaunty/gnupg2/jaunty-security

« back to all changes in this revision

Viewing changes to g10/keygen.c

  • Committer: Bazaar Package Importer
  • Author(s): Thomas Viehmann
  • Date: 2008-10-04 10:25:53 UTC
  • mfrom: (5.1.15 intrepid)
  • Revision ID: james.westby@ubuntu.com-20081004102553-fv62pp8dsitxli47
Tags: 2.0.9-3.1
* Non-maintainer upload.
* agent/gpg-agent.c: Deinit the threading library before exec'ing
  the command to run in --daemon mode. And because that still doesn't
  restore the sigprocmask, do that manually. Closes: #499569

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