Fix a typo in the X.509v3 docs: cRLSign instead of cRLCertSign is correct
[openssl.git] / apps / req.c
1 /* apps/req.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <time.h>
62 #include <string.h>
63 #ifdef NO_STDIO
64 #define APPS_WIN16
65 #endif
66 #include "apps.h"
67 #include "bio.h"
68 #include "evp.h"
69 #include "rand.h"
70 #include "conf.h"
71 #include "err.h"
72 #include "asn1.h"
73 #include "x509.h"
74 #include "x509v3.h"
75 #include "objects.h"
76 #include "pem.h"
77
78 #define SECTION         "req"
79
80 #define BITS            "default_bits"
81 #define KEYFILE         "default_keyfile"
82 #define DISTINGUISHED_NAME      "distinguished_name"
83 #define ATTRIBUTES      "attributes"
84 #define V3_EXTENSIONS   "x509_extensions"
85
86 #define DEFAULT_KEY_LENGTH      512
87 #define MIN_KEY_LENGTH          384
88
89 #undef PROG
90 #define PROG    req_main
91
92 /* -inform arg  - input format - default PEM (one of DER, TXT or PEM)
93  * -outform arg - output format - default PEM
94  * -in arg      - input file - default stdin
95  * -out arg     - output file - default stdout
96  * -verify      - check request signature
97  * -noout       - don't print stuff out.
98  * -text        - print out human readable text.
99  * -nodes       - no des encryption
100  * -config file - Load configuration file.
101  * -key file    - make a request using key in file (or use it for verification).
102  * -keyform     - key file format.
103  * -newkey      - make a key and a request.
104  * -modulus     - print RSA modulus.
105  * -x509        - output a self signed X509 structure instead.
106  * -asn1-kludge - output new certificate request in a format that some CA's
107  *                require.  This format is wrong
108  */
109
110 #ifndef NOPROTO
111 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,int attribs);
112 static int add_attribute_object(STACK *n, char *text, char *def, 
113         char *value, int nid,int min,int max);
114 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
115         int nid,int min,int max);
116 static void MS_CALLBACK req_cb(int p,int n,char *arg);
117 static int req_fix_data(int nid,int *type,int len,int min,int max);
118 static int check_end(char *str, char *end);
119 static int add_oid_section(LHASH *conf);
120 #else
121 static int make_REQ();
122 static int add_attribute_object();
123 static int add_DN_object();
124 static void MS_CALLBACK req_cb();
125 static int req_fix_data();
126 static int check_end();
127 static int add_oid_section();
128 #endif
129
130 #ifndef MONOLITH
131 static char *default_config_file=NULL;
132 static LHASH *config=NULL;
133 #endif
134 static LHASH *req_conf=NULL;
135
136 #define TYPE_RSA        1
137 #define TYPE_DSA        2
138 #define TYPE_DH         3
139
140 int MAIN(argc, argv)
141 int argc;
142 char **argv;
143         {
144 #ifndef NO_DSA
145         DSA *dsa_params=NULL;
146 #endif
147         int ex=1,x509=0,days=30;
148         X509 *x509ss=NULL;
149         X509_REQ *req=NULL;
150         EVP_PKEY *pkey=NULL;
151         int i,badops=0,newreq=0,newkey= -1,pkey_type=0;
152         BIO *in=NULL,*out=NULL;
153         int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
154         int nodes=0,kludge=0;
155         char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
156         char *extensions = NULL;
157         EVP_CIPHER *cipher=NULL;
158         int modulus=0;
159         char *p;
160         EVP_MD *md_alg=NULL,*digest=EVP_md5();
161 #ifndef MONOLITH
162         MS_STATIC char config_name[256];
163 #endif
164
165 #ifndef NO_DES
166         cipher=EVP_des_ede3_cbc();
167 #endif
168         apps_startup();
169
170         if (bio_err == NULL)
171                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
172                         BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
173
174         infile=NULL;
175         outfile=NULL;
176         informat=FORMAT_PEM;
177         outformat=FORMAT_PEM;
178
179         prog=argv[0];
180         argc--;
181         argv++;
182         while (argc >= 1)
183                 {
184                 if      (strcmp(*argv,"-inform") == 0)
185                         {
186                         if (--argc < 1) goto bad;
187                         informat=str2fmt(*(++argv));
188                         }
189                 else if (strcmp(*argv,"-outform") == 0)
190                         {
191                         if (--argc < 1) goto bad;
192                         outformat=str2fmt(*(++argv));
193                         }
194                 else if (strcmp(*argv,"-key") == 0)
195                         {
196                         if (--argc < 1) goto bad;
197                         keyfile= *(++argv);
198                         }
199                 else if (strcmp(*argv,"-new") == 0)
200                         {
201                         pkey_type=TYPE_RSA;
202                         newreq=1;
203                         }
204                 else if (strcmp(*argv,"-config") == 0)
205                         {       
206                         if (--argc < 1) goto bad;
207                         template= *(++argv);
208                         }
209                 else if (strcmp(*argv,"-keyform") == 0)
210                         {
211                         if (--argc < 1) goto bad;
212                         keyform=str2fmt(*(++argv));
213                         }
214                 else if (strcmp(*argv,"-in") == 0)
215                         {
216                         if (--argc < 1) goto bad;
217                         infile= *(++argv);
218                         }
219                 else if (strcmp(*argv,"-out") == 0)
220                         {
221                         if (--argc < 1) goto bad;
222                         outfile= *(++argv);
223                         }
224                 else if (strcmp(*argv,"-keyout") == 0)
225                         {
226                         if (--argc < 1) goto bad;
227                         keyout= *(++argv);
228                         }
229                 else if (strcmp(*argv,"-newkey") == 0)
230                         {
231                         int is_numeric;
232
233                         if (--argc < 1) goto bad;
234                         p= *(++argv);
235                         is_numeric = p[0] >= '0' && p[0] <= '9';
236                         if (strncmp("rsa:",p,4) == 0 || is_numeric)
237                                 {
238                                 pkey_type=TYPE_RSA;
239                                 if(!is_numeric)
240                                     p+=4;
241                                 newkey= atoi(p);
242                                 }
243                         else
244 #ifndef NO_DSA
245                                 if (strncmp("dsa:",p,4) == 0)
246                                 {
247                                 X509 *xtmp=NULL;
248                                 EVP_PKEY *dtmp;
249
250                                 pkey_type=TYPE_DSA;
251                                 p+=4;
252                                 if ((in=BIO_new_file(p,"r")) == NULL)
253                                         {
254                                         perror(p);
255                                         goto end;
256                                         }
257                                 if ((dsa_params=PEM_read_bio_DSAparams(in,NULL,NULL)) == NULL)
258                                         {
259                                         ERR_clear_error();
260                                         BIO_reset(in);
261                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL)) == NULL)
262                                                 {
263                                                 BIO_printf(bio_err,"unable to load DSA parameters from file\n");
264                                                 goto end;
265                                                 }
266
267                                         dtmp=X509_get_pubkey(xtmp);
268                                         if (dtmp->type == EVP_PKEY_DSA)
269                                                 dsa_params=DSAparams_dup(dtmp->pkey.dsa);
270                                         EVP_PKEY_free(dtmp);
271                                         X509_free(xtmp);
272                                         if (dsa_params == NULL)
273                                                 {
274                                                 BIO_printf(bio_err,"Certificate does not contain DSA parameters\n");
275                                                 goto end;
276                                                 }
277                                         }
278                                 BIO_free(in);
279                                 newkey=BN_num_bits(dsa_params->p);
280                                 in=NULL;
281                                 }
282                         else 
283 #endif
284 #ifndef NO_DH
285                                 if (strncmp("dh:",p,4) == 0)
286                                 {
287                                 pkey_type=TYPE_DH;
288                                 p+=3;
289                                 }
290                         else
291 #endif
292                                 pkey_type=TYPE_RSA;
293
294                         newreq=1;
295                         }
296                 else if (strcmp(*argv,"-modulus") == 0)
297                         modulus=1;
298                 else if (strcmp(*argv,"-verify") == 0)
299                         verify=1;
300                 else if (strcmp(*argv,"-nodes") == 0)
301                         nodes=1;
302                 else if (strcmp(*argv,"-noout") == 0)
303                         noout=1;
304                 else if (strcmp(*argv,"-text") == 0)
305                         text=1;
306                 else if (strcmp(*argv,"-x509") == 0)
307                         x509=1;
308                 else if (strcmp(*argv,"-asn1-kludge") == 0)
309                         kludge=1;
310                 else if (strcmp(*argv,"-no-asn1-kludge") == 0)
311                         kludge=0;
312                 else if (strcmp(*argv,"-days") == 0)
313                         {
314                         if (--argc < 1) goto bad;
315                         days= atoi(*(++argv));
316                         if (days == 0) days=30;
317                         }
318                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
319                         {
320                         /* ok */
321                         digest=md_alg;
322                         }
323                 else
324
325                         {
326                         BIO_printf(bio_err,"unknown option %s\n",*argv);
327                         badops=1;
328                         break;
329                         }
330                 argc--;
331                 argv++;
332                 }
333
334         if (badops)
335                 {
336 bad:
337                 BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
338                 BIO_printf(bio_err,"where options  are\n");
339                 BIO_printf(bio_err," -inform arg    input format - one of DER TXT PEM\n");
340                 BIO_printf(bio_err," -outform arg   output format - one of DER TXT PEM\n");
341                 BIO_printf(bio_err," -in arg        input file\n");
342                 BIO_printf(bio_err," -out arg       output file\n");
343                 BIO_printf(bio_err," -text          text form of request\n");
344                 BIO_printf(bio_err," -noout         do not output REQ\n");
345                 BIO_printf(bio_err," -verify        verify signature on REQ\n");
346                 BIO_printf(bio_err," -modulus       RSA modulus\n");
347                 BIO_printf(bio_err," -nodes         don't encrypt the output key\n");
348                 BIO_printf(bio_err," -key file  use the private key contained in file\n");
349                 BIO_printf(bio_err," -keyform arg   key file format\n");
350                 BIO_printf(bio_err," -keyout arg    file to send the key to\n");
351                 BIO_printf(bio_err," -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
352                 BIO_printf(bio_err," -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
353
354                 BIO_printf(bio_err," -[digest]      Digest to sign with (md5, sha1, md2, mdc2)\n");
355                 BIO_printf(bio_err," -config file   request template file.\n");
356                 BIO_printf(bio_err," -new           new request.\n");
357                 BIO_printf(bio_err," -x509          output a x509 structure instead of a cert. req.\n");
358                 BIO_printf(bio_err," -days          number of days a x509 generated by -x509 is valid for.\n");
359                 BIO_printf(bio_err," -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
360                 BIO_printf(bio_err,"                have been reported as requiring\n");
361                 BIO_printf(bio_err,"                [ It is now always turned on but can be turned off with -no-asn1-kludge ]\n");
362                 goto end;
363                 }
364
365         ERR_load_crypto_strings();
366         X509V3_add_standard_extensions();
367
368 #ifndef MONOLITH
369         /* Lets load up our environment a little */
370         p=getenv("OPENSSL_CONF");
371         if (p == NULL)
372                 p=getenv("SSLEAY_CONF");
373         if (p == NULL)
374                 {
375                 strcpy(config_name,X509_get_default_cert_area());
376                 strcat(config_name,"/lib/");
377                 strcat(config_name,OPENSSL_CONF);
378                 p=config_name;
379                 }
380         default_config_file=p;
381         config=CONF_load(config,p,NULL);
382 #endif
383
384         if (template != NULL)
385                 {
386                 long errline;
387
388                 BIO_printf(bio_err,"Using configuration from %s\n",template);
389                 req_conf=CONF_load(NULL,template,&errline);
390                 if (req_conf == NULL)
391                         {
392                         BIO_printf(bio_err,"error on line %ld of %s\n",errline,template);
393                         goto end;
394                         }
395                 }
396         else
397                 {
398                 req_conf=config;
399                 BIO_printf(bio_err,"Using configuration from %s\n",
400                         default_config_file);
401                 if (req_conf == NULL)
402                         {
403                         BIO_printf(bio_err,"Unable to load config info\n");
404                         }
405                 }
406
407         if (req_conf != NULL)
408                 {
409                 p=CONF_get_string(req_conf,NULL,"oid_file");
410                 if (p != NULL)
411                         {
412                         BIO *oid_bio;
413
414                         oid_bio=BIO_new_file(p,"r");
415                         if (oid_bio == NULL) 
416                                 {
417                                 /*
418                                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
419                                 ERR_print_errors(bio_err);
420                                 */
421                                 }
422                         else
423                                 {
424                                 OBJ_create_objects(oid_bio);
425                                 BIO_free(oid_bio);
426                                 }
427                         }
428                 }
429                 if(!add_oid_section(req_conf)) goto end;
430
431         if ((md_alg == NULL) &&
432                 ((p=CONF_get_string(req_conf,SECTION,"default_md")) != NULL))
433                 {
434                 if ((md_alg=EVP_get_digestbyname(p)) != NULL)
435                         digest=md_alg;
436                 }
437
438         extensions = CONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
439         if(extensions) {
440                 /* Check syntax of file */
441                 if(!X509V3_EXT_check_conf(req_conf, extensions)) {
442                         BIO_printf(bio_err,
443                          "Error Loading extension section %s\n", extensions);
444                         goto end;
445                 }
446         }
447
448         in=BIO_new(BIO_s_file());
449         out=BIO_new(BIO_s_file());
450         if ((in == NULL) || (out == NULL))
451                 goto end;
452
453         if (keyfile != NULL)
454                 {
455                 if (BIO_read_filename(in,keyfile) <= 0)
456                         {
457                         perror(keyfile);
458                         goto end;
459                         }
460
461 /*              if (keyform == FORMAT_ASN1)
462                         rsa=d2i_RSAPrivateKey_bio(in,NULL);
463                 else */
464                 if (keyform == FORMAT_PEM)
465                         pkey=PEM_read_bio_PrivateKey(in,NULL,NULL);
466                 else
467                         {
468                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
469                         goto end;
470                         }
471
472                 if (pkey == NULL)
473                         {
474                         BIO_printf(bio_err,"unable to load Private key\n");
475                         goto end;
476                         }
477                 }
478
479         if (newreq && (pkey == NULL))
480                 {
481                 char *randfile;
482                 char buffer[200];
483
484                 if ((randfile=CONF_get_string(req_conf,SECTION,"RANDFILE")) == NULL)
485                         randfile=RAND_file_name(buffer,200);
486 #ifdef WINDOWS
487                 BIO_printf(bio_err,"Loading 'screen' into random state -");
488                 BIO_flush(bio_err);
489                 RAND_screen();
490                 BIO_printf(bio_err," done\n");
491 #endif
492                 if ((randfile == NULL) || !RAND_load_file(randfile,1024L*1024L))
493                         {
494                         BIO_printf(bio_err,"unable to load 'random state'\n");
495                         BIO_printf(bio_err,"What this means is that the random number generator has not been seeded\n");
496                         BIO_printf(bio_err,"with much random data.\n");
497                         BIO_printf(bio_err,"Consider setting the RANDFILE environment variable to point at a file that\n");
498                         BIO_printf(bio_err,"'random' data can be kept in.\n");
499                         }
500                 if (newkey <= 0)
501                         {
502                         newkey=(int)CONF_get_number(req_conf,SECTION,BITS);
503                         if (newkey <= 0)
504                                 newkey=DEFAULT_KEY_LENGTH;
505                         }
506
507                 if (newkey < MIN_KEY_LENGTH)
508                         {
509                         BIO_printf(bio_err,"private key length is too short,\n");
510                         BIO_printf(bio_err,"it needs to be at least %d bits, not %d\n",MIN_KEY_LENGTH,newkey);
511                         goto end;
512                         }
513                 BIO_printf(bio_err,"Generating a %d bit %s private key\n",
514                         newkey,(pkey_type == TYPE_RSA)?"RSA":"DSA");
515
516                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
517
518 #ifndef NO_RSA
519                 if (pkey_type == TYPE_RSA)
520                         {
521                         if (!EVP_PKEY_assign_RSA(pkey,
522                                 RSA_generate_key(newkey,0x10001,
523                                         req_cb,(char *)bio_err)))
524                                 goto end;
525                         }
526                 else
527 #endif
528 #ifndef NO_DSA
529                         if (pkey_type == TYPE_DSA)
530                         {
531                         if (!DSA_generate_key(dsa_params)) goto end;
532                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
533                         dsa_params=NULL;
534                         }
535 #endif
536
537                 if ((randfile == NULL) || (RAND_write_file(randfile) == 0))
538                         BIO_printf(bio_err,"unable to write 'random state'\n");
539
540                 if (pkey == NULL) goto end;
541
542                 if (keyout == NULL)
543                         keyout=CONF_get_string(req_conf,SECTION,KEYFILE);
544
545                 if (keyout == NULL)
546                         {
547                         BIO_printf(bio_err,"writing new private key to stdout\n");
548                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
549                         }
550                 else
551                         {
552                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
553                         if (BIO_write_filename(out,keyout) <= 0)
554                                 {
555                                 perror(keyout);
556                                 goto end;
557                                 }
558                         }
559
560                 p=CONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
561                 if (p == NULL)
562                         p=CONF_get_string(req_conf,SECTION,"encrypt_key");
563                 if ((p != NULL) && (strcmp(p,"no") == 0))
564                         cipher=NULL;
565                 if (nodes) cipher=NULL;
566                 
567                 i=0;
568 loop:
569                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
570                         NULL,0,NULL))
571                         {
572                         if ((ERR_GET_REASON(ERR_peek_error()) ==
573                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
574                                 {
575                                 ERR_clear_error();
576                                 i++;
577                                 goto loop;
578                                 }
579                         goto end;
580                         }
581                 BIO_printf(bio_err,"-----\n");
582                 }
583
584         if (!newreq)
585                 {
586                 /* Since we are using a pre-existing certificate
587                  * request, the kludge 'format' info should not be
588                  * changed. */
589                 kludge= -1;
590                 if (infile == NULL)
591                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
592                 else
593                         {
594                         if (BIO_read_filename(in,infile) <= 0)
595                                 {
596                                 perror(infile);
597                                 goto end;
598                                 }
599                         }
600
601                 if      (informat == FORMAT_ASN1)
602                         req=d2i_X509_REQ_bio(in,NULL);
603                 else if (informat == FORMAT_PEM)
604                         req=PEM_read_bio_X509_REQ(in,NULL,NULL);
605                 else
606                         {
607                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
608                         goto end;
609                         }
610                 if (req == NULL)
611                         {
612                         BIO_printf(bio_err,"unable to load X509 request\n");
613                         goto end;
614                         }
615                 }
616
617         if (newreq || x509)
618                 {
619 #ifndef NO_DSA
620                 if (pkey->type == EVP_PKEY_DSA)
621                         digest=EVP_dss1();
622 #endif
623
624                 if (pkey == NULL)
625                         {
626                         BIO_printf(bio_err,"you need to specify a private key\n");
627                         goto end;
628                         }
629                 if (req == NULL)
630                         {
631                         req=X509_REQ_new();
632                         if (req == NULL)
633                                 {
634                                 goto end;
635                                 }
636
637                         i=make_REQ(req,pkey,!x509);
638                         if (kludge >= 0)
639                                 req->req_info->req_kludge=kludge;
640                         if (!i)
641                                 {
642                                 BIO_printf(bio_err,"problems making Certificate Request\n");
643                                 goto end;
644                                 }
645                         }
646                 if (x509)
647                         {
648                         EVP_PKEY *tmppkey;
649                         X509V3_CTX ext_ctx;
650                         if ((x509ss=X509_new()) == NULL) goto end;
651
652                         /* Set version to V3 */
653                         if(!X509_set_version(x509ss, 2)) goto end;
654                         ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L);
655
656                         X509_set_issuer_name(x509ss,
657                                 X509_REQ_get_subject_name(req));
658                         X509_gmtime_adj(X509_get_notBefore(x509ss),0);
659                         X509_gmtime_adj(X509_get_notAfter(x509ss),
660                                 (long)60*60*24*days);
661                         X509_set_subject_name(x509ss,
662                                 X509_REQ_get_subject_name(req));
663                         tmppkey = X509_REQ_get_pubkey(req);
664                         X509_set_pubkey(x509ss,tmppkey);
665                         EVP_PKEY_free(tmppkey);
666
667                         /* Set up V3 context struct */
668
669                         ext_ctx.issuer_cert = x509ss;
670                         ext_ctx.subject_cert = x509ss;
671                         ext_ctx.subject_req = NULL;
672                         ext_ctx.crl = NULL;
673                         ext_ctx.flags = 0;
674
675                         /* Add extensions */
676                         if(extensions && !X509V3_EXT_add_conf(req_conf, 
677                                         &ext_ctx, extensions, x509ss))
678                             {
679                             BIO_printf(bio_err,
680                                        "Error Loading extension section %s\n",
681                                        extensions);
682                             goto end;
683                             }
684
685                         if (!(i=X509_sign(x509ss,pkey,digest)))
686                                 goto end;
687                         }
688                 else
689                         {
690                         if (!(i=X509_REQ_sign(req,pkey,digest)))
691                                 goto end;
692                         }
693                 }
694
695         if (verify && !x509)
696                 {
697                 int tmp=0;
698
699                 if (pkey == NULL)
700                         {
701                         pkey=X509_REQ_get_pubkey(req);
702                         tmp=1;
703                         if (pkey == NULL) goto end;
704                         }
705
706                 i=X509_REQ_verify(req,pkey);
707                 if (tmp) {
708                         EVP_PKEY_free(pkey);
709                         pkey=NULL;
710                 }
711
712                 if (i < 0)
713                         {
714                         goto end;
715                         }
716                 else if (i == 0)
717                         {
718                         BIO_printf(bio_err,"verify failure\n");
719                         }
720                 else /* if (i > 0) */
721                         BIO_printf(bio_err,"verify OK\n");
722                 }
723
724         if (noout && !text && !modulus)
725                 {
726                 ex=0;
727                 goto end;
728                 }
729
730         if (outfile == NULL)
731                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
732         else
733                 {
734                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
735                         i=(int)BIO_append_filename(out,outfile);
736                 else
737                         i=(int)BIO_write_filename(out,outfile);
738                 if (!i)
739                         {
740                         perror(outfile);
741                         goto end;
742                         }
743                 }
744
745         if (text)
746                 {
747                 if (x509)
748                         X509_print(out,x509ss);
749                 else    
750                         X509_REQ_print(out,req);
751                 }
752
753         if (modulus)
754                 {
755                 EVP_PKEY *pubkey;
756
757                 if (x509)
758                         pubkey=X509_get_pubkey(x509ss);
759                 else
760                         pubkey=X509_REQ_get_pubkey(req);
761                 if (pubkey == NULL)
762                         {
763                         fprintf(stdout,"Modulus=unavailable\n");
764                         goto end; 
765                         }
766                 fprintf(stdout,"Modulus=");
767 #ifndef NO_RSA
768                 if (pubkey->type == EVP_PKEY_RSA)
769                         BN_print(out,pubkey->pkey.rsa->n);
770                 else
771 #endif
772                         fprintf(stdout,"Wrong Algorithm type");
773                 fprintf(stdout,"\n");
774                 }
775
776         if (!noout && !x509)
777                 {
778                 if      (outformat == FORMAT_ASN1)
779                         i=i2d_X509_REQ_bio(out,req);
780                 else if (outformat == FORMAT_PEM)
781                         i=PEM_write_bio_X509_REQ(out,req);
782                 else    {
783                         BIO_printf(bio_err,"bad output format specified for outfile\n");
784                         goto end;
785                         }
786                 if (!i)
787                         {
788                         BIO_printf(bio_err,"unable to write X509 request\n");
789                         goto end;
790                         }
791                 }
792         if (!noout && x509 && (x509ss != NULL))
793                 {
794                 if      (outformat == FORMAT_ASN1)
795                         i=i2d_X509_bio(out,x509ss);
796                 else if (outformat == FORMAT_PEM)
797                         i=PEM_write_bio_X509(out,x509ss);
798                 else    {
799                         BIO_printf(bio_err,"bad output format specified for outfile\n");
800                         goto end;
801                         }
802                 if (!i)
803                         {
804                         BIO_printf(bio_err,"unable to write X509 certificate\n");
805                         goto end;
806                         }
807                 }
808         ex=0;
809 end:
810         if (ex)
811                 {
812                 ERR_print_errors(bio_err);
813                 }
814         if ((req_conf != NULL) && (req_conf != config)) CONF_free(req_conf);
815         BIO_free(in);
816         BIO_free(out);
817         EVP_PKEY_free(pkey);
818         X509_REQ_free(req);
819         X509_free(x509ss);
820         X509V3_EXT_cleanup();
821         OBJ_cleanup();
822 #ifndef NO_DSA
823         if (dsa_params != NULL) DSA_free(dsa_params);
824 #endif
825         EXIT(ex);
826         }
827
828 static int make_REQ(req,pkey,attribs)
829 X509_REQ *req;
830 EVP_PKEY *pkey;
831 int attribs;
832         {
833         int ret=0,i;
834         unsigned char *p,*q;
835         X509_REQ_INFO *ri;
836         char buf[100];
837         int nid,min,max;
838         char *type,*def,*tmp,*value,*tmp_attr;
839         STACK *sk,*attr=NULL;
840         CONF_VALUE *v;
841         
842         tmp=CONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
843         if (tmp == NULL)
844                 {
845                 BIO_printf(bio_err,"unable to find '%s' in config\n",
846                         DISTINGUISHED_NAME);
847                 goto err;
848                 }
849         sk=CONF_get_section(req_conf,tmp);
850         if (sk == NULL)
851                 {
852                 BIO_printf(bio_err,"unable to get '%s' section\n",tmp);
853                 goto err;
854                 }
855
856         tmp_attr=CONF_get_string(req_conf,SECTION,ATTRIBUTES);
857         if (tmp_attr == NULL)
858                 attr=NULL;
859         else
860                 {
861                 attr=CONF_get_section(req_conf,tmp_attr);
862                 if (attr == NULL)
863                         {
864                         BIO_printf(bio_err,"unable to get '%s' section\n",tmp_attr);
865                         goto err;
866                         }
867                 }
868
869         ri=req->req_info;
870
871         BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
872         BIO_printf(bio_err,"into your certificate request.\n");
873         BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
874         BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
875         BIO_printf(bio_err,"For some fields there will be a default value,\n");
876         BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
877         BIO_printf(bio_err,"-----\n");
878
879         /* setup version number */
880         if (!ASN1_INTEGER_set(ri->version,0L)) goto err; /* version 1 */
881
882         if (sk_num(sk))
883                 {
884                 i= -1;
885 start:          for (;;)
886                         {
887                         i++;
888                         if ((int)sk_num(sk) <= i) break;
889
890                         v=(CONF_VALUE *)sk_value(sk,i);
891                         p=q=NULL;
892                         type=v->name;
893                         if(!check_end(type,"_min") || !check_end(type,"_max") ||
894                                 !check_end(type,"_default") ||
895                                          !check_end(type,"_value")) continue;
896                         /* Skip past any leading X. X: X, etc to allow for
897                          * multiple instances 
898                          */
899                         for(p = v->name; *p ; p++) 
900                                 if ((*p == ':') || (*p == ',') ||
901                                                          (*p == '.')) {
902                                         p++;
903                                         if(*p) type = p;
904                                         break;
905                                 }
906                         /* If OBJ not recognised ignore it */
907                         if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
908                         sprintf(buf,"%s_default",v->name);
909                         if ((def=CONF_get_string(req_conf,tmp,buf)) == NULL)
910                                 def="";
911                                 
912                         sprintf(buf,"%s_value",v->name);
913                         if ((value=CONF_get_string(req_conf,tmp,buf)) == NULL)
914                                 value=NULL;
915
916                         sprintf(buf,"%s_min",v->name);
917                         min=(int)CONF_get_number(req_conf,tmp,buf);
918
919                         sprintf(buf,"%s_max",v->name);
920                         max=(int)CONF_get_number(req_conf,tmp,buf);
921
922                         if (!add_DN_object(ri->subject,v->value,def,value,nid,
923                                 min,max))
924                                 goto err;
925                         }
926                 if (sk_num(ri->subject->entries) == 0)
927                         {
928                         BIO_printf(bio_err,"error, no objects specified in config file\n");
929                         goto err;
930                         }
931
932                 if (attribs)
933                         {
934                         if ((attr != NULL) && (sk_num(attr) > 0))
935                                 {
936                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
937                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
938                                 }
939
940                         i= -1;
941 start2:                 for (;;)
942                                 {
943                                 i++;
944                                 if ((attr == NULL) || ((int)sk_num(attr) <= i))
945                                         break;
946
947                                 v=(CONF_VALUE *)sk_value(attr,i);
948                                 type=v->name;
949                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
950                                         goto start2;
951
952                                 sprintf(buf,"%s_default",type);
953                                 if ((def=CONF_get_string(req_conf,tmp_attr,buf))
954                                         == NULL)
955                                         def="";
956                                 
957                                 sprintf(buf,"%s_value",type);
958                                 if ((value=CONF_get_string(req_conf,tmp_attr,buf))
959                                         == NULL)
960                                         value=NULL;
961
962                                 sprintf(buf,"%s_min",type);
963                                 min=(int)CONF_get_number(req_conf,tmp_attr,buf);
964
965                                 sprintf(buf,"%s_max",type);
966                                 max=(int)CONF_get_number(req_conf,tmp_attr,buf);
967
968                                 if (!add_attribute_object(ri->attributes,
969                                         v->value,def,value,nid,min,max))
970                                         goto err;
971                                 }
972                         }
973                 }
974         else
975                 {
976                 BIO_printf(bio_err,"No template, please set one up.\n");
977                 goto err;
978                 }
979
980         X509_REQ_set_pubkey(req,pkey);
981
982         ret=1;
983 err:
984         return(ret);
985         }
986
987 static int add_DN_object(n,text,def,value,nid,min,max)
988 X509_NAME *n;
989 char *text;
990 char *def;
991 char *value;
992 int nid;
993 int min;
994 int max;
995         {
996         int i,j,ret=0;
997         X509_NAME_ENTRY *ne=NULL;
998         MS_STATIC char buf[1024];
999
1000         BIO_printf(bio_err,"%s [%s]:",text,def);
1001         BIO_flush(bio_err);
1002         if (value != NULL)
1003                 {
1004                 strcpy(buf,value);
1005                 strcat(buf,"\n");
1006                 BIO_printf(bio_err,"%s\n",value);
1007                 }
1008         else
1009                 {
1010                 buf[0]='\0';
1011                 fgets(buf,1024,stdin);
1012                 }
1013
1014         if (buf[0] == '\0') return(0);
1015         else if (buf[0] == '\n')
1016                 {
1017                 if ((def == NULL) || (def[0] == '\0'))
1018                         return(1);
1019                 strcpy(buf,def);
1020                 strcat(buf,"\n");
1021                 }
1022         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1023
1024         i=strlen(buf);
1025         if (buf[i-1] != '\n')
1026                 {
1027                 BIO_printf(bio_err,"weird input :-(\n");
1028                 return(0);
1029                 }
1030         buf[--i]='\0';
1031
1032         j=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1033         if (req_fix_data(nid,&j,i,min,max) == 0)
1034                 goto err;
1035         if ((ne=X509_NAME_ENTRY_create_by_NID(NULL,nid,j,(unsigned char *)buf,
1036                 strlen(buf)))
1037                 == NULL) goto err;
1038         if (!X509_NAME_add_entry(n,ne,X509_NAME_entry_count(n),0))
1039                 goto err;
1040
1041         ret=1;
1042 err:
1043         if (ne != NULL) X509_NAME_ENTRY_free(ne);
1044         return(ret);
1045         }
1046
1047 static int add_attribute_object(n,text,def,value,nid,min,max)
1048 STACK *n;
1049 char *text;
1050 char *def;
1051 char *value;
1052 int nid;
1053 int min;
1054 int max;
1055         {
1056         int i,z;
1057         X509_ATTRIBUTE *xa=NULL;
1058         static char buf[1024];
1059         ASN1_BIT_STRING *bs=NULL;
1060         ASN1_TYPE *at=NULL;
1061
1062 start:
1063         BIO_printf(bio_err,"%s [%s]:",text,def);
1064         BIO_flush(bio_err);
1065         if (value != NULL)
1066                 {
1067                 strcpy(buf,value);
1068                 strcat(buf,"\n");
1069                 BIO_printf(bio_err,"%s\n",value);
1070                 }
1071         else
1072                 {
1073                 buf[0]='\0';
1074                 fgets(buf,1024,stdin);
1075                 }
1076
1077         if (buf[0] == '\0') return(0);
1078         else if (buf[0] == '\n')
1079                 {
1080                 if ((def == NULL) || (def[0] == '\0'))
1081                         return(1);
1082                 strcpy(buf,def);
1083                 strcat(buf,"\n");
1084                 }
1085         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1086
1087         i=strlen(buf);
1088         if (buf[i-1] != '\n')
1089                 {
1090                 BIO_printf(bio_err,"weird input :-(\n");
1091                 return(0);
1092                 }
1093         buf[--i]='\0';
1094
1095         /* add object plus value */
1096         if ((xa=X509_ATTRIBUTE_new()) == NULL)
1097                 goto err;
1098         if ((xa->value.set=sk_new_null()) == NULL)
1099                 goto err;
1100         xa->set=1;
1101
1102         if (xa->object != NULL) ASN1_OBJECT_free(xa->object);
1103         xa->object=OBJ_nid2obj(nid);
1104
1105         if ((bs=ASN1_BIT_STRING_new()) == NULL) goto err;
1106
1107         bs->type=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1108
1109         z=req_fix_data(nid,&bs->type,i,min,max);
1110         if (z == 0)
1111                 {
1112                 if (value == NULL)
1113                         goto start;
1114                 else    goto err;
1115                 }
1116
1117         if (!ASN1_STRING_set(bs,(unsigned char *)buf,i+1))
1118                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1119
1120         if ((at=ASN1_TYPE_new()) == NULL)
1121                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1122
1123         ASN1_TYPE_set(at,bs->type,(char *)bs);
1124         sk_push(xa->value.set,(char *)at);
1125         bs=NULL;
1126         at=NULL;
1127         /* only one item per attribute */
1128
1129         if (!sk_push(n,(char *)xa)) goto err;
1130         return(1);
1131 err:
1132         if (xa != NULL) X509_ATTRIBUTE_free(xa);
1133         if (at != NULL) ASN1_TYPE_free(at);
1134         if (bs != NULL) ASN1_BIT_STRING_free(bs);
1135         return(0);
1136         }
1137
1138 static void MS_CALLBACK req_cb(p,n,arg)
1139 int p;
1140 int n;
1141 char *arg;
1142         {
1143         char c='*';
1144
1145         if (p == 0) c='.';
1146         if (p == 1) c='+';
1147         if (p == 2) c='*';
1148         if (p == 3) c='\n';
1149         BIO_write((BIO *)arg,&c,1);
1150         BIO_flush((BIO *)arg);
1151 #ifdef LINT
1152         p=n;
1153 #endif
1154         }
1155
1156 static int req_fix_data(nid,type,len,min,max)
1157 int nid;
1158 int *type;
1159 int len,min,max;
1160         {
1161         if (nid == NID_pkcs9_emailAddress)
1162                 *type=V_ASN1_IA5STRING;
1163         if ((nid == NID_commonName) && (*type == V_ASN1_IA5STRING))
1164                 *type=V_ASN1_T61STRING;
1165         if ((nid == NID_pkcs9_challengePassword) &&
1166                 (*type == V_ASN1_IA5STRING))
1167                 *type=V_ASN1_T61STRING;
1168
1169         if ((nid == NID_pkcs9_unstructuredName) &&
1170                 (*type == V_ASN1_T61STRING))
1171                 {
1172                 BIO_printf(bio_err,"invalid characters in string, please re-enter the string\n");
1173                 return(0);
1174                 }
1175         if (nid == NID_pkcs9_unstructuredName)
1176                 *type=V_ASN1_IA5STRING;
1177
1178         if (len < min)
1179                 {
1180                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",min);
1181                 return(0);
1182                 }
1183         if ((max != 0) && (len > max))
1184                 {
1185                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",max);
1186                 return(0);
1187                 }
1188         return(1);
1189         }
1190
1191 /* Check if the end of a string matches 'end' */
1192 static int check_end(str, end)
1193 char *str;
1194 char *end;
1195 {
1196         int elen, slen; 
1197         char *tmp;
1198         elen = strlen(end);
1199         slen = strlen(str);
1200         if(elen > slen) return 1;
1201         tmp = str + slen - elen;
1202         return strcmp(tmp, end);
1203 }
1204
1205 static int add_oid_section(conf)
1206 LHASH *conf;
1207 {       
1208         char *p;
1209         STACK *sktmp;
1210         CONF_VALUE *cnf;
1211         int i;
1212         if(!(p=CONF_get_string(conf,NULL,"oid_section"))) return 1;
1213         if(!(sktmp = CONF_get_section(conf, p))) {
1214                 BIO_printf(bio_err, "problem loading oid section %s\n", p);
1215                 return 0;
1216         }
1217         for(i = 0; i < sk_num(sktmp); i++) {
1218                 cnf = (CONF_VALUE *)sk_value(sktmp, i);
1219                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
1220                         BIO_printf(bio_err, "problem creating object %s=%s\n",
1221                                                          cnf->name, cnf->value);
1222                         return 0;
1223                 }
1224         }
1225         return 1;
1226 }