summaryrefslogtreecommitdiffstats
path: root/sm/certreqgen.c
blob: 7d0bfbd6feacaeeef903c50c50a77f30e3fe3c40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
/* certreqgen.c - Generate a key and a certification [request]
 * Copyright (C) 2002, 2003, 2005, 2007, 2010,
 *               2011 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

/*
The format of the native parameter file is follows:
  o Text only, line length is limited to about 1000 chars.
  o You must use UTF-8 encoding to specify non-ascii characters.
  o Empty lines are ignored.
  o Leading and trailing spaces are ignored.
  o A hash sign as the first non white space character is a comment line.
  o Control statements are indicated by a leading percent sign, the
    arguments are separated by white space from the keyword.
  o Parameters are specified by a keyword, followed by a colon.  Arguments
    are separated by white space.
  o The first parameter must be "Key-Type", control statements
    may be placed anywhere.
  o Key generation takes place when either the end of the parameter file
    is reached, the next "Key-Type" parameter is encountered or at the
    controlstatement "%commit"
  o Control statements:
    %echo <text>
	Print <text>.
    %dry-run
	Suppress actual key generation (useful for syntax checking).
    %commit
	Perform the key generation.  Note that an implicit commit is done
	at the next "Key-Type" parameter.
    %certfile <filename>
        [Not yet implemented!]
	Do not write the certificate to the keyDB but to <filename>.
        This must be given before the first
	commit to take place, duplicate specification of the same filename
	is ignored, the last filename before a commit is used.
	The filename is used until a new filename is used (at commit points)
	and all keys are written to that file.	If a new filename is given,
	this file is created (and overwrites an existing one).
	Both control statements must be given.

   o The order of the parameters does not matter except for "Key-Type"
     which must be the first parameter.  The parameters are only for the
     generated keyblock and parameters from previous key generations are not
     used. Some syntactically checks may be performed.

     The currently defined parameters are:

     Key-Type: <algo>
	Starts a new parameter block by giving the type of the
	primary key. The algorithm must be capable of signing.
	This is a required parameter.  For now the only supported
        algorithm is "rsa".

     Key-Length: <length-in-bits>
	Length of the key in bits.  Default is 2048.

     Key-Grip: <hexstring>
        This is optional and used to generate a request for an already
        existing key.  Key-Length will be ignored when given,

     Key-Usage: <usage-list>
        Space or comma delimited list of key usage, allowed values are
        "encrypt" and "sign".  This is used to generate the KeyUsage extension.
        Please make sure that the algorithm is capable of this usage.  Default
        is to allow encrypt and sign.

     Name-DN: <subject_name>
        This is the DN name of the subject in rfc2253 format.

     Name-Email: <string>
	The is an email address for the altSubjectName

     Name-DNS: <string>
	The is an DNS name for the altSubjectName

     Name-URI: <string>
	The is an URI for the altSubjectName

     The following parameters are only used if a certificate (and not
     a certificate signing request) is requested:

     Serial: <sn>
        If this parameter is given an X.509 certificate will be
        generated.  SN is expected to be a hex string representing an
        unsigned integer of arbitary length.  The special value
        "random" can be used to crete a 64 bit random serial number.

     Issuer-DN: <issuer_name>
        This is the DN name of the issuer in rfc2253 format.  If it is
        not set the subject DN will be used instead.  This creates a
        self-signed certificate.  Only in this case a special GnuPG
        extension will then be included in the certificate to mark it
        as a standalone certificate.

     Creation-Date: <iso-date>
        Set the notBefore date of the certificate.  Either a date like
        "1986-04-26" or a full timestamp like "19860426T042640" may be
        used.  The time is considered to be UTC.  If it is not given
        the current date is used.

     Expire-Date: <iso-date>
        Set the notBefore date of the certificate.  Either a date like
        "1986-04-26" or a full timestamp like "19860426T042640" may be
        used.  The time is considered to be UTC.  If it is not given a
        default value is used.

     Signing-Key: <keygrip>
        This gives the keygrip of the key used to sign the
        certificate.  If it is not given a self-signed certificate
        will be created.

     Hash-Algo: <hash-algo>
        Use HASH-ALGO for this certificate.  The supported hash
        algorithms are: "sha-1", "sha-256", "sha-384" and "sha-512".
        "sha-1" is the default.

Here is an example:
$ cat >foo <<EOF
%echo Generating a standard key
Key-Type: RSA
Key-Length: 2048
Name-DN: CN=test cert 1,OU=Aegypten Project,O=g10 Code GmbH,L=Düsseldorf,C=DE
Name-Email: joe@foo.bar
# Do a commit here, so that we can later print "done" :-)
%commit
%echo done
EOF
*/


#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>

#include "gpgsm.h"
#include <gcrypt.h>
#include <ksba.h>

#include "keydb.h"
#include "i18n.h"


enum para_name
  {
    pKEYTYPE,
    pKEYLENGTH,
    pKEYGRIP,
    pKEYUSAGE,
    pNAMEDN,
    pNAMEEMAIL,
    pNAMEDNS,
    pNAMEURI,
    pSERIAL,
    pISSUERDN,
    pNOTBEFORE,
    pNOTAFTER,
    pSIGNINGKEY,
    pHASHALGO
  };

struct para_data_s
{
  struct para_data_s *next;
  int lnr;
  enum para_name key;
  union {
    unsigned int usage;
    char value[1];
  } u;
};

struct reqgen_ctrl_s
{
  int lnr;
  int dryrun;
};


static const char oidstr_keyUsage[] = "2.5.29.15";
static const char oidstr_basicConstraints[] = "2.5.29.19";
static const char oidstr_standaloneCertificate[] = "1.3.6.1.4.1.11591.2.2.1";


static int proc_parameters (ctrl_t ctrl,
                            struct para_data_s *para,
                            estream_t out_fp,
                            struct reqgen_ctrl_s *outctrl);
static int create_request (ctrl_t ctrl,
                           struct para_data_s *para,
                           const char *carddirect,
                           ksba_const_sexp_t public,
                           ksba_const_sexp_t sigkey,
                           ksba_writer_t writer);



static void
release_parameter_list (struct para_data_s *r)
{
  struct para_data_s *r2;

  for (; r ; r = r2)
    {
      r2 = r->next;
      xfree(r);
    }
}

static struct para_data_s *
get_parameter (struct para_data_s *para, enum para_name key, int seq)
{
  struct para_data_s *r;

  for (r = para; r ; r = r->next)
    if ( r->key == key && !seq--)
      return r;
  return NULL;
}

static const char *
get_parameter_value (struct para_data_s *para, enum para_name key, int seq)
{
  struct para_data_s *r = get_parameter (para, key, seq);
  return (r && *r->u.value)? r->u.value : NULL;
}

static int
get_parameter_algo (struct para_data_s *para, enum para_name key)
{
  struct para_data_s *r = get_parameter (para, key, 0);
  if (!r)
    return -1;
  if (digitp (r->u.value))
    return atoi( r->u.value );
  return gcry_pk_map_name (r->u.value);
}

/* Parse the usage parameter.  Returns 0 on success.  Note that we
   only care about sign and encrypt and don't (yet) allow all the
   other X.509 usage to be specified; instead we will use a fixed
   mapping to the X.509 usage flags. */
static int
parse_parameter_usage (struct para_data_s *para, enum para_name key)
{
  struct para_data_s *r = get_parameter (para, key, 0);
  char *p, *pn;
  unsigned int use;

  if (!r)
    return 0; /* none (this is an optional parameter)*/

  use = 0;
  pn = r->u.value;
  while ( (p = strsep (&pn, " \t,")) )
    {
      if (!*p)
        ;
      else if ( !ascii_strcasecmp (p, "sign") )
        use |= GCRY_PK_USAGE_SIGN;
      else if ( !ascii_strcasecmp (p, "encrypt") )
        use |= GCRY_PK_USAGE_ENCR;
      else
        {
          log_error ("line %d: invalid usage list\n", r->lnr);
          return -1; /* error */
        }
    }
  r->u.usage = use;
  return 0;
}


static unsigned int
get_parameter_uint (struct para_data_s *para, enum para_name key)
{
  struct para_data_s *r = get_parameter (para, key, 0);

  if (!r)
    return 0;

  if (r->key == pKEYUSAGE)
    return r->u.usage;

  return (unsigned int)strtoul (r->u.value, NULL, 10);
}



/* Read the certificate generation parameters from FP and generate
   (all) certificate requests.  */
static int
read_parameters (ctrl_t ctrl, estream_t fp, estream_t out_fp)
{
  static struct {
    const char *name;
    enum para_name key;
    int allow_dups;
  } keywords[] = {
    { "Key-Type",       pKEYTYPE},
    { "Key-Length",     pKEYLENGTH },
    { "Key-Grip",       pKEYGRIP },
    { "Key-Usage",      pKEYUSAGE },
    { "Name-DN",        pNAMEDN },
    { "Name-Email",     pNAMEEMAIL, 1 },
    { "Name-DNS",       pNAMEDNS, 1 },
    { "Name-URI",       pNAMEURI, 1 },
    { "Serial",         pSERIAL },
    { "Issuer-DN",      pISSUERDN },
    { "Creation-Date",  pNOTBEFORE },
    { "Not-Before",     pNOTBEFORE },
    { "Expire-Date",    pNOTAFTER },
    { "Not-After",      pNOTAFTER },
    { "Signing-Key",    pSIGNINGKEY },
    { "Hash-Algo",      pHASHALGO },
    { NULL, 0 }
  };
  char line[1024], *p;
  const char *err = NULL;
  struct para_data_s *para, *r;
  int i, rc = 0, any = 0;
  struct reqgen_ctrl_s outctrl;

  memset (&outctrl, 0, sizeof (outctrl));

  err = NULL;
  para = NULL;
  while (es_fgets (line, DIM(line)-1, fp) )
    {
      char *keyword, *value;

      outctrl.lnr++;
      if (*line && line[strlen(line)-1] != '\n')
        {
          err = "line too long";
          break;
	}
      for (p=line; spacep (p); p++)
        ;
      if (!*p || *p == '#')
        continue;

      keyword = p;
      if (*keyword == '%')
        {
          for (; *p && !ascii_isspace (*p); p++)
            ;
          if (*p)
            *p++ = 0;
          for (; ascii_isspace (*p); p++)
            ;
          value = p;
          trim_trailing_spaces (value);

          if (!ascii_strcasecmp (keyword, "%echo"))
            log_info ("%s\n", value);
          else if (!ascii_strcasecmp (keyword, "%dry-run"))
            outctrl.dryrun = 1;
          else if (!ascii_strcasecmp( keyword, "%commit"))
            {
              rc = proc_parameters (ctrl, para, out_fp, &outctrl);
              if (rc)
                goto leave;
              any = 1;
              release_parameter_list (para);
              para = NULL;
	    }
          else
            log_info ("skipping control `%s' (%s)\n", keyword, value);

          continue;
	}


      if (!(p = strchr (p, ':')) || p == keyword)
        {
          err = "missing colon";
          break;
	}
      if (*p)
        *p++ = 0;
      for (; spacep (p); p++)
        ;
      if (!*p)
        {
          err = "missing argument";
          break;
	}
      value = p;
      trim_trailing_spaces (value);

      for (i=0; (keywords[i].name
                 && ascii_strcasecmp (keywords[i].name, keyword)); i++)
        ;
      if (!keywords[i].name)
        {
          err = "unknown keyword";
          break;
	}
      if (keywords[i].key != pKEYTYPE && !para)
        {
          err = "parameter block does not start with \"Key-Type\"";
          break;
	}

      if (keywords[i].key == pKEYTYPE && para)
        {
          rc = proc_parameters (ctrl, para, out_fp, &outctrl);
          if (rc)
            goto leave;
          any = 1;
          release_parameter_list (para);
          para = NULL;
	}
      else if (!keywords[i].allow_dups)
        {
          for (r = para; r && r->key != keywords[i].key; r = r->next)
            ;
          if (r)
            {
              err = "duplicate keyword";
              break;
	    }
	}

      r = xtrycalloc (1, sizeof *r + strlen( value ));
      if (!r)
        {
          err = "out of core";
          break;
        }
      r->lnr = outctrl.lnr;
      r->key = keywords[i].key;
      strcpy (r->u.value, value);
      r->next = para;
      para = r;
    }

  if (err)
    {
      log_error ("line %d: %s\n", outctrl.lnr, err);
      rc = gpg_error (GPG_ERR_GENERAL);
    }
  else if (es_ferror(fp))
    {
      log_error ("line %d: read error: %s\n", outctrl.lnr, strerror(errno) );
      rc = gpg_error (GPG_ERR_GENERAL);
    }
  else if (para)
    {
      rc = proc_parameters (ctrl, para, out_fp, &outctrl);
      if (rc)
        goto leave;
      any = 1;
    }

  if (!rc && !any)
    rc = gpg_error (GPG_ERR_NO_DATA);

 leave:
  release_parameter_list (para);
  return rc;
}

/* check whether there are invalid characters in the email address S */
static int
has_invalid_email_chars (const char *s)
{
  int at_seen=0;
  static char valid_chars[] = "01234567890_-."
                              "abcdefghijklmnopqrstuvwxyz"
			      "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for (; *s; s++)
    {
      if (*s & 0x80)
        return 1;
      if (*s == '@')
        at_seen++;
      else if (!at_seen && !( !!strchr (valid_chars, *s) || *s == '+'))
        return 1;
      else if (at_seen && !strchr (valid_chars, *s))
        return 1;
    }
  return at_seen != 1;
}


/* Check that all required parameters are given and perform the action */
static int
proc_parameters (ctrl_t ctrl, struct para_data_s *para,
                 estream_t out_fp, struct reqgen_ctrl_s *outctrl)
{
  gpg_error_t err;
  struct para_data_s *r;
  const char *s, *string;
  int i;
  unsigned int nbits;
  char numbuf[20];
  unsigned char keyparms[100];
  int rc;
  ksba_sexp_t public;
  ksba_sexp_t sigkey = NULL;
  int seq;
  size_t erroff, errlen;
  char *cardkeyid = NULL;

  /* Check that we have all required parameters; */
  assert (get_parameter (para, pKEYTYPE, 0));

  /* We can only use RSA for now.  There is a problem with pkcs-10 on
     how to use ElGamal because it is expected that a PK algorithm can
     always be used for signing. Another problem is that on-card
     generated encryption keys may not be used for signing.  */
  i = get_parameter_algo (para, pKEYTYPE);
  if (!i && (s = get_parameter_value (para, pKEYTYPE, 0)) && *s)
    {
      /* Hack to allow creation of certificates directly from a smart
         card.  For example: "Key-Type: card:OPENPGP.3".  */
      if (!strncmp (s, "card:", 5) && s[5])
        cardkeyid = xtrystrdup (s+5);
    }
  if ( (i < 1 || i != GCRY_PK_RSA) && !cardkeyid )
    {
      r = get_parameter (para, pKEYTYPE, 0);
      log_error (_("line %d: invalid algorithm\n"), r->lnr);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }

  /* Check the keylength.  NOTE: If you change this make sure that it
     macthes the gpgconflist item in gpgsm.c  */
  if (!get_parameter (para, pKEYLENGTH, 0))
    nbits = 2048;
  else
    nbits = get_parameter_uint (para, pKEYLENGTH);
  if ((nbits < 1024 || nbits > 4096) && !cardkeyid)
    {
      /* The BSI specs dated 2002-11-25 don't allow lengths below 1024. */
      r = get_parameter (para, pKEYLENGTH, 0);
      log_error (_("line %d: invalid key length %u (valid are %d to %d)\n"),
                 r->lnr, nbits, 1024, 4096);
      xfree (cardkeyid);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }

  /* Check the usage. */
  if (parse_parameter_usage (para, pKEYUSAGE))
    {
      xfree (cardkeyid);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }

  /* Check that there is a subject name and that this DN fits our
     requirements. */
  if (!(s=get_parameter_value (para, pNAMEDN, 0)))
    {
      r = get_parameter (para, pNAMEDN, 0);
      log_error (_("line %d: no subject name given\n"), r->lnr);
      xfree (cardkeyid);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }
  err = ksba_dn_teststr (s, 0, &erroff, &errlen);
  if (err)
    {
      r = get_parameter (para, pNAMEDN, 0);
      if (gpg_err_code (err) == GPG_ERR_UNKNOWN_NAME)
        log_error (_("line %d: invalid subject name label `%.*s'\n"),
                   r->lnr, (int)errlen, s+erroff);
      else
        log_error (_("line %d: invalid subject name `%s' at pos %d\n"),
                   r->lnr, s, (int)erroff);

      xfree (cardkeyid);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }

  /* Check that the optional email address is okay. */
  for (seq=0; (s=get_parameter_value (para, pNAMEEMAIL, seq)); seq++)
    {
      if (has_invalid_email_chars (s)
          || *s == '@'
          || s[strlen(s)-1] == '@'
          || s[strlen(s)-1] == '.'
          || strstr(s, ".."))
        {
          r = get_parameter (para, pNAMEEMAIL, seq);
          log_error (_("line %d: not a valid email address\n"), r->lnr);
          xfree (cardkeyid);
          return gpg_error (GPG_ERR_INV_PARAMETER);
        }
    }

  /* Check the optional serial number.  */
  string = get_parameter_value (para, pSERIAL, 0);
  if (string)
    {
      if (!strcmp (string, "random"))
        ; /* Okay.  */
      else
        {
          for (s=string, i=0; hexdigitp (s); s++, i++)
            ;
          if (*s)
            {
              r = get_parameter (para, pSERIAL, 0);
              log_error (_("line %d: invalid serial number\n"), r->lnr);
              xfree (cardkeyid);
              return gpg_error (GPG_ERR_INV_PARAMETER);
            }
        }
    }

  /* Check the optional issuer DN.  */
  string = get_parameter_value (para, pISSUERDN, 0);
  if (string)
    {
      err = ksba_dn_teststr (string, 0, &erroff, &errlen);
      if (err)
        {
          r = get_parameter (para, pISSUERDN, 0);
          if (gpg_err_code (err) == GPG_ERR_UNKNOWN_NAME)
            log_error (_("line %d: invalid issuer name label `%.*s'\n"),
                       r->lnr, (int)errlen, string+erroff);
          else
            log_error (_("line %d: invalid issuer name `%s' at pos %d\n"),
                       r->lnr, string, (int)erroff);
          xfree (cardkeyid);
          return gpg_error (GPG_ERR_INV_PARAMETER);
        }
    }

  /* Check the optional creation date.  */
  string = get_parameter_value (para, pNOTBEFORE, 0);
  if (string && !string2isotime (NULL, string))
    {
      r = get_parameter (para, pNOTBEFORE, 0);
      log_error (_("line %d: invalid date given\n"), r->lnr);
      xfree (cardkeyid);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }


  /* Check the optional expire date.  */
  string = get_parameter_value (para, pNOTAFTER, 0);
  if (string && !string2isotime (NULL, string))
    {
      r = get_parameter (para, pNOTAFTER, 0);
      log_error (_("line %d: invalid date given\n"), r->lnr);
      xfree (cardkeyid);
      return gpg_error (GPG_ERR_INV_PARAMETER);
    }

  /* Get the optional signing key.  */
  string = get_parameter_value (para, pSIGNINGKEY, 0);
  if (string)
    {
      rc = gpgsm_agent_readkey (ctrl, 0, string, &sigkey);
      if (rc)
        {
          r = get_parameter (para, pKEYTYPE, 0);
          log_error (_("line %d: error getting signing key by keygrip `%s'"
                       ": %s\n"), r->lnr, s, gpg_strerror (rc));
          xfree (cardkeyid);
          return rc;
        }
    }

  /* Check the optional hash-algo.  */
  {
    int mdalgo;

    string = get_parameter_value (para, pHASHALGO, 0);
    if (string && !((mdalgo = gcry_md_map_name (string))
                    && (mdalgo == GCRY_MD_SHA1
                        || mdalgo == GCRY_MD_SHA256
                        || mdalgo == GCRY_MD_SHA384
                        || mdalgo == GCRY_MD_SHA512)))
      {
        r = get_parameter (para, pHASHALGO, 0);
        log_error (_("line %d: invalid hash algorithm given\n"), r->lnr);
        xfree (cardkeyid);
        return gpg_error (GPG_ERR_INV_PARAMETER);
      }
  }

  /* Create or retrieve the public key.  */
  if (cardkeyid) /* Take the key from the current smart card. */
    {
      rc = gpgsm_agent_readkey (ctrl, 1, cardkeyid, &public);
      if (rc)
        {
          r = get_parameter (para, pKEYTYPE, 0);
          log_error (_("line %d: error reading key `%s' from card: %s\n"),
                     r->lnr, cardkeyid, gpg_strerror (rc));
          xfree (sigkey);
          xfree (cardkeyid);
          return rc;
        }
    }
  else if ((s=get_parameter_value (para, pKEYGRIP, 0))) /* Use existing key.*/
    {
      rc = gpgsm_agent_readkey (ctrl, 0, s, &public);
      if (rc)
        {
          r = get_parameter (para, pKEYTYPE, 0);
          log_error (_("line %d: error getting key by keygrip `%s': %s\n"),
                     r->lnr, s, gpg_strerror (rc));
          xfree (sigkey);
          xfree (cardkeyid);
          return rc;
        }
    }
  else if (!outctrl->dryrun) /* Generate new key.  */
    {
      sprintf (numbuf, "%u", nbits);
      snprintf ((char*)keyparms, DIM (keyparms)-1,
                "(6:genkey(3:rsa(5:nbits%d:%s)))",
                (int)strlen (numbuf), numbuf);
      rc = gpgsm_agent_genkey (ctrl, keyparms, &public);
      if (rc)
        {
          r = get_parameter (para, pKEYTYPE, 0);
          log_error (_("line %d: key generation failed: %s <%s>\n"),
                     r->lnr, gpg_strerror (rc), gpg_strsource (rc));
          xfree (sigkey);
          xfree (cardkeyid);
          return rc;
        }
    }


  if (!outctrl->dryrun)
    {
      Base64Context b64writer = NULL;
      ksba_writer_t writer;
      int create_cert ;

      create_cert = !!get_parameter_value (para, pSERIAL, 0);

      ctrl->pem_name = create_cert? "CERTIFICATE" : "CERTIFICATE REQUEST";
      rc = gpgsm_create_writer (&b64writer, ctrl, out_fp, &writer);
      if (rc)
        log_error ("can't create writer: %s\n", gpg_strerror (rc));
      else
        {
          rc = create_request (ctrl, para, cardkeyid, public, sigkey, writer);
          if (!rc)
            {
              rc = gpgsm_finish_writer (b64writer);
              if (rc)
                log_error ("write failed: %s\n", gpg_strerror (rc));
              else
                {
                  gpgsm_status (ctrl, STATUS_KEY_CREATED, "P");
                  log_info ("certificate%s created\n",
                            create_cert?"":" request");
                }
            }
          gpgsm_destroy_writer (b64writer);
        }
    }

  xfree (sigkey);
  xfree (public);
  xfree (cardkeyid);

  return rc;
}


/* Parameters are checked, the key pair has been created.  Now
   generate the request and write it out */
static int
create_request (ctrl_t ctrl,
                struct para_data_s *para,
                const char *carddirect,
                ksba_const_sexp_t public,
                ksba_const_sexp_t sigkey,
                ksba_writer_t writer)
{
  ksba_certreq_t cr;
  gpg_error_t err;
  gcry_md_hd_t md;
  ksba_stop_reason_t stopreason;
  int rc = 0;
  const char *s, *string;
  unsigned int use;
  int seq;
  char *buf, *p;
  size_t len;
  char numbuf[30];
  ksba_isotime_t atime;
  int certmode = 0;
  int mdalgo;

  err = ksba_certreq_new (&cr);
  if (err)
    return err;

  string = get_parameter_value (para, pHASHALGO, 0);
  if (string)
    mdalgo = gcry_md_map_name (string);
  else
    mdalgo = GCRY_MD_SHA1;
  rc = gcry_md_open (&md, mdalgo, 0);
  if (rc)
    {
      log_error ("md_open failed: %s\n", gpg_strerror (rc));
      goto leave;
    }
  if (DBG_HASHING)
    gcry_md_start_debug (md, "cr.cri");

  ksba_certreq_set_hash_function (cr, HASH_FNC, md);
  ksba_certreq_set_writer (cr, writer);

  err = ksba_certreq_add_subject (cr, get_parameter_value (para, pNAMEDN, 0));
  if (err)
    {
      log_error ("error setting the subject's name: %s\n",
                 gpg_strerror (err));
      rc = err;
      goto leave;
    }

  for (seq=0; (s = get_parameter_value (para, pNAMEEMAIL, seq)); seq++)
    {
      buf = xtrymalloc (strlen (s) + 3);
      if (!buf)
        {
          rc = out_of_core ();
          goto leave;
        }
      *buf = '<';
      strcpy (buf+1, s);
      strcat (buf+1, ">");
      err = ksba_certreq_add_subject (cr, buf);
      xfree (buf);
      if (err)
        {
          log_error ("error setting the subject's alternate name: %s\n",
                     gpg_strerror (err));
          rc = err;
          goto leave;
        }
    }

  for (seq=0; (s = get_parameter_value (para, pNAMEDNS, seq)); seq++)
    {
      len = strlen (s);
      assert (len);
      snprintf (numbuf, DIM(numbuf), "%u:", (unsigned int)len);
      buf = p = xtrymalloc (11 + strlen (numbuf) + len + 3);
      if (!buf)
        {
          rc = out_of_core ();
          goto leave;
        }
      p = stpcpy (p, "(8:dns-name");
      p = stpcpy (p, numbuf);
      p = stpcpy (p, s);
      strcpy (p, ")");

      err = ksba_certreq_add_subject (cr, buf);
      xfree (buf);
      if (err)
        {
          log_error ("error setting the subject's alternate name: %s\n",
                     gpg_strerror (err));
          rc = err;
          goto leave;
        }
    }

  for (seq=0; (s = get_parameter_value (para, pNAMEURI, seq)); seq++)
    {
      len = strlen (s);
      assert (len);
      snprintf (numbuf, DIM(numbuf), "%u:", (unsigned int)len);
      buf = p = xtrymalloc (6 + strlen (numbuf) + len + 3);
      if (!buf)
        {
          rc = out_of_core ();
          goto leave;
        }
      p = stpcpy (p, "(3:uri");
      p = stpcpy (p, numbuf);
      p = stpcpy (p, s);
      strcpy (p, ")");

      err = ksba_certreq_add_subject (cr, buf);
      xfree (buf);
      if (err)
        {
          log_error ("error setting the subject's alternate name: %s\n",
                     gpg_strerror (err));
          rc = err;
          goto leave;
        }
    }


  err = ksba_certreq_set_public_key (cr, public);
  if (err)
    {
      log_error ("error setting the public key: %s\n",
                 gpg_strerror (err));
      rc = err;
      goto leave;
    }

  /* Set key usage flags.  */
  use = get_parameter_uint (para, pKEYUSAGE);
  if (use == GCRY_PK_USAGE_SIGN)
    {
      /* For signing only we encode the bits:
         KSBA_KEYUSAGE_DIGITAL_SIGNATURE
         KSBA_KEYUSAGE_NON_REPUDIATION */
      err = ksba_certreq_add_extension (cr, oidstr_keyUsage, 1,
                                        "\x03\x02\x06\xC0", 4);
    }
  else if (use == GCRY_PK_USAGE_ENCR)
    {
      /* For encrypt only we encode the bits:
         KSBA_KEYUSAGE_KEY_ENCIPHERMENT
         KSBA_KEYUSAGE_DATA_ENCIPHERMENT */
      err = ksba_certreq_add_extension (cr, oidstr_keyUsage, 1,
                                        "\x03\x02\x04\x30", 4);
    }
  else
    err = 0; /* Both or none given: don't request one. */
  if (err)
    {
      log_error ("error setting the key usage: %s\n",
                 gpg_strerror (err));
      rc = err;
      goto leave;
    }


  /* See whether we want to create an X.509 certificate.  */
  string = get_parameter_value (para, pSERIAL, 0);
  if (string)
    {
      certmode = 1;

      /* Store the serial number.  */
      if (!strcmp (string, "random"))
        {
          char snbuf[3+8+1];

          memcpy (snbuf, "(8:", 3);
          gcry_create_nonce (snbuf+3, 8);
          /* Clear high bit to guarantee a positive integer.  */
          snbuf[3] &= 0x7f;
          snbuf[3+8] = ')';
          err = ksba_certreq_set_serial (cr, snbuf);
        }
      else
        {
          char *hexbuf;

          /* Allocate a buffer large enough to prefix the string with
             a '0' so to have an even number of digits.  Prepend two
             further '0' so that the binary result will have a leading
             0 byte and thus can't be the representation of a negative
             number.  Note that ksba_certreq_set_serial strips all
             unneeded leading 0 bytes.  */
          hexbuf = p = xtrymalloc (2 + 1 + strlen (string) + 1);
          if (!hexbuf)
            {
              err = gpg_error_from_syserror ();
              goto leave;
            }
          if ((strlen (string) & 1))
            *p++ = '0';
          *p++ = '0';
          *p++ = '0';
          strcpy (p, string);
          for (p=hexbuf, len=0; p[0] && p[1]; p += 2)
            ((unsigned char*)hexbuf)[len++] = xtoi_2 (s);
          /* Now build the S-expression.  */
          snprintf (numbuf, DIM(numbuf), "%u:", (unsigned int)len);
          buf = p = xtrymalloc (1 + strlen (numbuf) + len + 1 + 1);
          if (!buf)
            {
              err = gpg_error_from_syserror ();
              xfree (hexbuf);
              goto leave;
            }
          p = stpcpy (stpcpy (buf, "("), numbuf);
          memcpy (p, hexbuf, len);
          p += len;
          strcpy (p, ")");
          xfree (hexbuf);
          err = ksba_certreq_set_serial (cr, buf);
          xfree (buf);
        }
      if (err)
        {
          log_error ("error setting the serial number: %s\n",
                     gpg_strerror (err));
          goto leave;
        }


      /* Store the issuer DN.  If no issuer DN is given and no signing
         key has been set we add the standalone extension and the
         basic constraints to mark it as a self-signed CA
         certificate.  */
      string = get_parameter_value (para, pISSUERDN, 0);
      if (string)
        {
          /* Issuer DN given.  Note that this may be the same as the
             subject DN and thus this could as well be a self-signed
             certificate.  However the caller needs to explicitly
             specify basicConstraints and so forth.  */
          err = ksba_certreq_set_issuer (cr, string);
          if (err)
            {
              log_error ("error setting the issuer DN: %s\n",
                         gpg_strerror (err));
              goto leave;
            }

        }
      else if (!string && !sigkey)
        {
          /* Self-signed certificate requested.  Add basicConstraints
             and the custom GnuPG standalone extension.  */
          err = ksba_certreq_add_extension (cr, oidstr_basicConstraints, 1,
                                            "\x30\x03\x01\x01\xff", 5);
          if (err)
            goto leave;
          err = ksba_certreq_add_extension (cr, oidstr_standaloneCertificate, 0,
                                            "\x01\x01\xff", 3);
          if (err)
            goto leave;
        }

      /* Store the creation date.  */
      string = get_parameter_value (para, pNOTBEFORE, 0);
      if (string)
        {
          if (!string2isotime (atime, string))
            BUG (); /* We already checked the value.  */
        }
      else
        gnupg_get_isotime (atime);
      err = ksba_certreq_set_validity (cr, 0, atime);
      if (err)
        {
          log_error ("error setting the creation date: %s\n",
                     gpg_strerror (err));
          goto leave;
        }


      /* Store the expire date.  If it is not given, libksba inserts a
         default value.  */
      string = get_parameter_value (para, pNOTAFTER, 0);
      if (string)
        {
          if (!string2isotime (atime, string))
            BUG (); /* We already checked the value.  */
          err = ksba_certreq_set_validity (cr, 1, atime);
          if (err)
            {
              log_error ("error setting the expire date: %s\n",
                         gpg_strerror (err));
              goto leave;
            }
        }


      /* Figure out the signing algorithm.  If no sigkey has been
         given we set it to the public key to create a self-signed
         certificate. */
      if (!sigkey)
        sigkey = public;

      {
        unsigned char *siginfo;

        err = transform_sigval (sigkey,
                                gcry_sexp_canon_len (sigkey, 0, NULL, NULL),
                                mdalgo, &siginfo, NULL);
        if (!err)
          {
            err = ksba_certreq_set_siginfo (cr, siginfo);
            xfree (siginfo);
          }
        if (err)
          {
            log_error ("error setting the siginfo: %s\n",
                       gpg_strerror (err));
            rc = err;
            goto leave;
          }
      }
    }
  else
    sigkey = public;

  do
    {
      err = ksba_certreq_build (cr, &stopreason);
      if (err)
        {
          log_error ("ksba_certreq_build failed: %s\n", gpg_strerror (err));
          rc = err;
          goto leave;
        }
      if (stopreason == KSBA_SR_NEED_SIG)
        {
          gcry_sexp_t s_pkey;
          size_t n;
          unsigned char grip[20];
          char hexgrip[41];
          unsigned char *sigval, *newsigval;
          size_t siglen;

          n = gcry_sexp_canon_len (sigkey, 0, NULL, NULL);
          if (!n)
            {
              log_error ("libksba did not return a proper S-Exp\n");
              rc = gpg_error (GPG_ERR_BUG);
              goto leave;
            }
          rc = gcry_sexp_sscan (&s_pkey, NULL, (const char*)sigkey, n);
          if (rc)
            {
              log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (rc));
              goto leave;
            }
          if ( !gcry_pk_get_keygrip (s_pkey, grip) )
            {
              rc = gpg_error (GPG_ERR_GENERAL);
              log_error ("can't figure out the keygrip\n");
              gcry_sexp_release (s_pkey);
              goto leave;
            }
          gcry_sexp_release (s_pkey);
          bin2hex (grip, 20, hexgrip);

          log_info ("about to sign the %s for key: &%s\n",
                    certmode? "certificate":"CSR", hexgrip);

          if (carddirect)
            rc = gpgsm_scd_pksign (ctrl, carddirect, NULL,
                                   gcry_md_read (md, mdalgo),
                                   gcry_md_get_algo_dlen (mdalgo),
                                   mdalgo,
                                   &sigval, &siglen);
          else
            {
              char *orig_codeset;
              char *desc;

              orig_codeset = i18n_switchto_utf8 ();
              desc = percent_plus_escape
                (_("To complete this certificate request please enter"
                   " the passphrase for the key you just created once"
                   " more.\n"));
              i18n_switchback (orig_codeset);
              rc = gpgsm_agent_pksign (ctrl, hexgrip, desc,
                                       gcry_md_read(md, mdalgo),
                                       gcry_md_get_algo_dlen (mdalgo),
                                       mdalgo,
                                       &sigval, &siglen);
              xfree (desc);
            }
          if (rc)
            {
              log_error ("signing failed: %s\n", gpg_strerror (rc));
              goto leave;
            }

          err = transform_sigval (sigval, siglen, mdalgo,
                                  &newsigval, NULL);
          xfree (sigval);
          if (!err)
            {
              err = ksba_certreq_set_sig_val (cr, newsigval);
              xfree (newsigval);
            }
          if (err)
            {
              log_error ("failed to store the sig_val: %s\n",
                         gpg_strerror (err));
              rc = err;
              goto leave;
            }
        }
    }
  while (stopreason != KSBA_SR_READY);


 leave:
  gcry_md_close (md);
  ksba_certreq_release (cr);
  return rc;
}



/* Create a new key by reading the parameters from IN_FP.  Multiple
   keys may be created */
int
gpgsm_genkey (ctrl_t ctrl, estream_t in_stream, estream_t out_stream)
{
  int rc;

  rc = read_parameters (ctrl, in_stream, out_stream);
  if (rc)
    {
      log_error ("error creating certificate request: %s <%s>\n",
                 gpg_strerror (rc), gpg_strsource (rc));
      goto leave;
    }

 leave:
  return rc;
}