Initial support for Certificate Policies extension: print out works but setting
[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         const 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                 X509V3_CTX ctx;
442                 X509V3_set_ctx_test(&ctx);
443                 X509V3_set_conf_lhash(&ctx, req_conf);
444                 if(!X509V3_EXT_add_conf(req_conf, &ctx, extensions, NULL)) {
445                         BIO_printf(bio_err,
446                          "Error Loading extension section %s\n", extensions);
447                         goto end;
448                 }
449         }
450
451         in=BIO_new(BIO_s_file());
452         out=BIO_new(BIO_s_file());
453         if ((in == NULL) || (out == NULL))
454                 goto end;
455
456         if (keyfile != NULL)
457                 {
458                 if (BIO_read_filename(in,keyfile) <= 0)
459                         {
460                         perror(keyfile);
461                         goto end;
462                         }
463
464 /*              if (keyform == FORMAT_ASN1)
465                         rsa=d2i_RSAPrivateKey_bio(in,NULL);
466                 else */
467                 if (keyform == FORMAT_PEM)
468                         pkey=PEM_read_bio_PrivateKey(in,NULL,NULL);
469                 else
470                         {
471                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
472                         goto end;
473                         }
474
475                 if (pkey == NULL)
476                         {
477                         BIO_printf(bio_err,"unable to load Private key\n");
478                         goto end;
479                         }
480                 }
481
482         if (newreq && (pkey == NULL))
483                 {
484                 char *randfile;
485                 char buffer[200];
486
487                 if ((randfile=CONF_get_string(req_conf,SECTION,"RANDFILE")) == NULL)
488                         randfile=RAND_file_name(buffer,200);
489 #ifdef WINDOWS
490                 BIO_printf(bio_err,"Loading 'screen' into random state -");
491                 BIO_flush(bio_err);
492                 RAND_screen();
493                 BIO_printf(bio_err," done\n");
494 #endif
495                 if ((randfile == NULL) || !RAND_load_file(randfile,1024L*1024L))
496                         {
497                         BIO_printf(bio_err,"unable to load 'random state'\n");
498                         BIO_printf(bio_err,"What this means is that the random number generator has not been seeded\n");
499                         BIO_printf(bio_err,"with much random data.\n");
500                         BIO_printf(bio_err,"Consider setting the RANDFILE environment variable to point at a file that\n");
501                         BIO_printf(bio_err,"'random' data can be kept in.\n");
502                         }
503                 if (newkey <= 0)
504                         {
505                         newkey=(int)CONF_get_number(req_conf,SECTION,BITS);
506                         if (newkey <= 0)
507                                 newkey=DEFAULT_KEY_LENGTH;
508                         }
509
510                 if (newkey < MIN_KEY_LENGTH)
511                         {
512                         BIO_printf(bio_err,"private key length is too short,\n");
513                         BIO_printf(bio_err,"it needs to be at least %d bits, not %d\n",MIN_KEY_LENGTH,newkey);
514                         goto end;
515                         }
516                 BIO_printf(bio_err,"Generating a %d bit %s private key\n",
517                         newkey,(pkey_type == TYPE_RSA)?"RSA":"DSA");
518
519                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
520
521 #ifndef NO_RSA
522                 if (pkey_type == TYPE_RSA)
523                         {
524                         if (!EVP_PKEY_assign_RSA(pkey,
525                                 RSA_generate_key(newkey,0x10001,
526                                         req_cb,(char *)bio_err)))
527                                 goto end;
528                         }
529                 else
530 #endif
531 #ifndef NO_DSA
532                         if (pkey_type == TYPE_DSA)
533                         {
534                         if (!DSA_generate_key(dsa_params)) goto end;
535                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
536                         dsa_params=NULL;
537                         }
538 #endif
539
540                 if ((randfile == NULL) || (RAND_write_file(randfile) == 0))
541                         BIO_printf(bio_err,"unable to write 'random state'\n");
542
543                 if (pkey == NULL) goto end;
544
545                 if (keyout == NULL)
546                         keyout=CONF_get_string(req_conf,SECTION,KEYFILE);
547
548                 if (keyout == NULL)
549                         {
550                         BIO_printf(bio_err,"writing new private key to stdout\n");
551                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
552                         }
553                 else
554                         {
555                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
556                         if (BIO_write_filename(out,keyout) <= 0)
557                                 {
558                                 perror(keyout);
559                                 goto end;
560                                 }
561                         }
562
563                 p=CONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
564                 if (p == NULL)
565                         p=CONF_get_string(req_conf,SECTION,"encrypt_key");
566                 if ((p != NULL) && (strcmp(p,"no") == 0))
567                         cipher=NULL;
568                 if (nodes) cipher=NULL;
569                 
570                 i=0;
571 loop:
572                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
573                         NULL,0,NULL))
574                         {
575                         if ((ERR_GET_REASON(ERR_peek_error()) ==
576                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
577                                 {
578                                 ERR_clear_error();
579                                 i++;
580                                 goto loop;
581                                 }
582                         goto end;
583                         }
584                 BIO_printf(bio_err,"-----\n");
585                 }
586
587         if (!newreq)
588                 {
589                 /* Since we are using a pre-existing certificate
590                  * request, the kludge 'format' info should not be
591                  * changed. */
592                 kludge= -1;
593                 if (infile == NULL)
594                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
595                 else
596                         {
597                         if (BIO_read_filename(in,infile) <= 0)
598                                 {
599                                 perror(infile);
600                                 goto end;
601                                 }
602                         }
603
604                 if      (informat == FORMAT_ASN1)
605                         req=d2i_X509_REQ_bio(in,NULL);
606                 else if (informat == FORMAT_PEM)
607                         req=PEM_read_bio_X509_REQ(in,NULL,NULL);
608                 else
609                         {
610                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
611                         goto end;
612                         }
613                 if (req == NULL)
614                         {
615                         BIO_printf(bio_err,"unable to load X509 request\n");
616                         goto end;
617                         }
618                 }
619
620         if (newreq || x509)
621                 {
622 #ifndef NO_DSA
623                 if (pkey->type == EVP_PKEY_DSA)
624                         digest=EVP_dss1();
625 #endif
626
627                 if (pkey == NULL)
628                         {
629                         BIO_printf(bio_err,"you need to specify a private key\n");
630                         goto end;
631                         }
632                 if (req == NULL)
633                         {
634                         req=X509_REQ_new();
635                         if (req == NULL)
636                                 {
637                                 goto end;
638                                 }
639
640                         i=make_REQ(req,pkey,!x509);
641                         if (kludge >= 0)
642                                 req->req_info->req_kludge=kludge;
643                         if (!i)
644                                 {
645                                 BIO_printf(bio_err,"problems making Certificate Request\n");
646                                 goto end;
647                                 }
648                         }
649                 if (x509)
650                         {
651                         EVP_PKEY *tmppkey;
652                         X509V3_CTX ext_ctx;
653                         if ((x509ss=X509_new()) == NULL) goto end;
654
655                         /* Set version to V3 */
656                         if(!X509_set_version(x509ss, 2)) goto end;
657                         ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L);
658
659                         X509_set_issuer_name(x509ss,
660                                 X509_REQ_get_subject_name(req));
661                         X509_gmtime_adj(X509_get_notBefore(x509ss),0);
662                         X509_gmtime_adj(X509_get_notAfter(x509ss),
663                                 (long)60*60*24*days);
664                         X509_set_subject_name(x509ss,
665                                 X509_REQ_get_subject_name(req));
666                         tmppkey = X509_REQ_get_pubkey(req);
667                         X509_set_pubkey(x509ss,tmppkey);
668                         EVP_PKEY_free(tmppkey);
669
670                         /* Set up V3 context struct */
671
672                         X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
673                         X509V3_set_conf_lhash(&ext_ctx, req_conf);
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 }