1f24be79bdd8709c783d3932149a7e81325baeef
[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 OPENSSL_NO_STDIO
64 #define APPS_WIN16
65 #endif
66 #include "apps.h"
67 #include <openssl/bio.h>
68 #include <openssl/evp.h>
69 #include <openssl/conf.h>
70 #include <openssl/err.h>
71 #include <openssl/asn1.h>
72 #include <openssl/x509.h>
73 #include <openssl/x509v3.h>
74 #include <openssl/objects.h>
75 #include <openssl/pem.h>
76
77 #define SECTION         "req"
78
79 #define BITS            "default_bits"
80 #define KEYFILE         "default_keyfile"
81 #define PROMPT          "prompt"
82 #define DISTINGUISHED_NAME      "distinguished_name"
83 #define ATTRIBUTES      "attributes"
84 #define V3_EXTENSIONS   "x509_extensions"
85 #define REQ_EXTENSIONS  "req_extensions"
86 #define STRING_MASK     "string_mask"
87 #define UTF8_IN         "utf8"
88
89 #define DEFAULT_KEY_LENGTH      512
90 #define MIN_KEY_LENGTH          384
91
92 #undef PROG
93 #define PROG    req_main
94
95 /* -inform arg  - input format - default PEM (DER or PEM)
96  * -outform arg - output format - default PEM
97  * -in arg      - input file - default stdin
98  * -out arg     - output file - default stdout
99  * -verify      - check request signature
100  * -noout       - don't print stuff out.
101  * -text        - print out human readable text.
102  * -nodes       - no des encryption
103  * -config file - Load configuration file.
104  * -key file    - make a request using key in file (or use it for verification).
105  * -keyform arg - key file format.
106  * -rand file(s) - load the file(s) into the PRNG.
107  * -newkey      - make a key and a request.
108  * -modulus     - print RSA modulus.
109  * -pubkey      - output Public Key.
110  * -x509        - output a self signed X509 structure instead.
111  * -asn1-kludge - output new certificate request in a format that some CA's
112  *                require.  This format is wrong
113  */
114
115 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,char *dn,int attribs,
116                 unsigned long chtype);
117 static int build_subject(X509_REQ *req, char *subj, unsigned long chtype);
118 static int prompt_info(X509_REQ *req,
119                 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
120                 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
121                 unsigned long chtype);
122 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
123                                 STACK_OF(CONF_VALUE) *attr, int attribs,
124                                 unsigned long chtype);
125 static int add_attribute_object(X509_REQ *req, char *text,
126                                 char *def, char *value, int nid, int n_min,
127                                 int n_max, unsigned long chtype);
128 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
129         int nid,int n_min,int n_max, unsigned long chtype);
130 #ifndef OPENSSL_NO_RSA
131 static void MS_CALLBACK req_cb(int p,int n,void *arg);
132 #endif
133 static int req_check_len(int len,int n_min,int n_max);
134 static int check_end(char *str, char *end);
135 #ifndef MONOLITH
136 static char *default_config_file=NULL;
137 static CONF *config=NULL;
138 #endif
139 static CONF *req_conf=NULL;
140 static int batch=0;
141
142 #define TYPE_RSA        1
143 #define TYPE_DSA        2
144 #define TYPE_DH         3
145 #define TYPE_EC         4
146
147 int MAIN(int, char **);
148
149 int MAIN(int argc, char **argv)
150         {
151         ENGINE *e = NULL;
152 #ifndef OPENSSL_NO_DSA
153         DSA *dsa_params=NULL;
154 #endif
155 #ifndef OPENSSL_NO_EC
156         EC_KEY *ec_params = NULL;
157 #endif
158         unsigned long nmflag = 0;
159         int ex=1,x509=0,days=30;
160         X509 *x509ss=NULL;
161         X509_REQ *req=NULL;
162         EVP_PKEY *pkey=NULL;
163         int i=0,badops=0,newreq=0,verbose=0,pkey_type=TYPE_RSA;
164         long newkey = -1;
165         BIO *in=NULL,*out=NULL;
166         int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
167         int nodes=0,kludge=0,newhdr=0,subject=0,pubkey=0;
168         char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
169         char *engine=NULL;
170         char *extensions = NULL;
171         char *req_exts = NULL;
172         const EVP_CIPHER *cipher=NULL;
173         ASN1_INTEGER *serial = NULL;
174         int modulus=0;
175         char *inrand=NULL;
176         char *passargin = NULL, *passargout = NULL;
177         char *passin = NULL, *passout = NULL;
178         char *p;
179         char *subj = NULL;
180         const EVP_MD *md_alg=NULL,*digest=EVP_md5();
181         unsigned long chtype = MBSTRING_ASC;
182 #ifndef MONOLITH
183         MS_STATIC char config_name[256];
184         long errline;
185 #endif
186
187         req_conf = NULL;
188 #ifndef OPENSSL_NO_DES
189         cipher=EVP_des_ede3_cbc();
190 #endif
191         apps_startup();
192
193         if (bio_err == NULL)
194                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
195                         BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
196
197         infile=NULL;
198         outfile=NULL;
199         informat=FORMAT_PEM;
200         outformat=FORMAT_PEM;
201
202         prog=argv[0];
203         argc--;
204         argv++;
205         while (argc >= 1)
206                 {
207                 if      (strcmp(*argv,"-inform") == 0)
208                         {
209                         if (--argc < 1) goto bad;
210                         informat=str2fmt(*(++argv));
211                         }
212                 else if (strcmp(*argv,"-outform") == 0)
213                         {
214                         if (--argc < 1) goto bad;
215                         outformat=str2fmt(*(++argv));
216                         }
217                 else if (strcmp(*argv,"-engine") == 0)
218                         {
219                         if (--argc < 1) goto bad;
220                         engine= *(++argv);
221                         }
222                 else if (strcmp(*argv,"-key") == 0)
223                         {
224                         if (--argc < 1) goto bad;
225                         keyfile= *(++argv);
226                         }
227                 else if (strcmp(*argv,"-pubkey") == 0)
228                         {
229                         pubkey=1;
230                         }
231                 else if (strcmp(*argv,"-new") == 0)
232                         {
233                         newreq=1;
234                         }
235                 else if (strcmp(*argv,"-config") == 0)
236                         {       
237                         if (--argc < 1) goto bad;
238                         template= *(++argv);
239                         }
240                 else if (strcmp(*argv,"-keyform") == 0)
241                         {
242                         if (--argc < 1) goto bad;
243                         keyform=str2fmt(*(++argv));
244                         }
245                 else if (strcmp(*argv,"-in") == 0)
246                         {
247                         if (--argc < 1) goto bad;
248                         infile= *(++argv);
249                         }
250                 else if (strcmp(*argv,"-out") == 0)
251                         {
252                         if (--argc < 1) goto bad;
253                         outfile= *(++argv);
254                         }
255                 else if (strcmp(*argv,"-keyout") == 0)
256                         {
257                         if (--argc < 1) goto bad;
258                         keyout= *(++argv);
259                         }
260                 else if (strcmp(*argv,"-passin") == 0)
261                         {
262                         if (--argc < 1) goto bad;
263                         passargin= *(++argv);
264                         }
265                 else if (strcmp(*argv,"-passout") == 0)
266                         {
267                         if (--argc < 1) goto bad;
268                         passargout= *(++argv);
269                         }
270                 else if (strcmp(*argv,"-rand") == 0)
271                         {
272                         if (--argc < 1) goto bad;
273                         inrand= *(++argv);
274                         }
275                 else if (strcmp(*argv,"-newkey") == 0)
276                         {
277                         int is_numeric;
278
279                         if (--argc < 1) goto bad;
280                         p= *(++argv);
281                         is_numeric = p[0] >= '0' && p[0] <= '9';
282                         if (strncmp("rsa:",p,4) == 0 || is_numeric)
283                                 {
284                                 pkey_type=TYPE_RSA;
285                                 if(!is_numeric)
286                                     p+=4;
287                                 newkey= atoi(p);
288                                 }
289                         else
290 #ifndef OPENSSL_NO_DSA
291                                 if (strncmp("dsa:",p,4) == 0)
292                                 {
293                                 X509 *xtmp=NULL;
294                                 EVP_PKEY *dtmp;
295
296                                 pkey_type=TYPE_DSA;
297                                 p+=4;
298                                 if ((in=BIO_new_file(p,"r")) == NULL)
299                                         {
300                                         perror(p);
301                                         goto end;
302                                         }
303                                 if ((dsa_params=PEM_read_bio_DSAparams(in,NULL,NULL,NULL)) == NULL)
304                                         {
305                                         ERR_clear_error();
306                                         (void)BIO_reset(in);
307                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL,NULL)) == NULL)
308                                                 {
309                                                 BIO_printf(bio_err,"unable to load DSA parameters from file\n");
310                                                 goto end;
311                                                 }
312
313                                         if ((dtmp=X509_get_pubkey(xtmp)) == NULL) goto end;
314                                         if (dtmp->type == EVP_PKEY_DSA)
315                                                 dsa_params=DSAparams_dup(dtmp->pkey.dsa);
316                                         EVP_PKEY_free(dtmp);
317                                         X509_free(xtmp);
318                                         if (dsa_params == NULL)
319                                                 {
320                                                 BIO_printf(bio_err,"Certificate does not contain DSA parameters\n");
321                                                 goto end;
322                                                 }
323                                         }
324                                 BIO_free(in);
325                                 in=NULL;
326                                 newkey=BN_num_bits(dsa_params->p);
327                                 }
328                         else 
329 #endif
330 #ifndef OPENSSL_NO_EC
331                                 if (strncmp("ecdsa:",p,4) == 0)
332                                 {
333                                 X509 *xtmp=NULL;
334                                 EVP_PKEY *dtmp;
335
336                                 pkey_type=TYPE_EC;
337                                 p+=6;
338                                 if ((in=BIO_new_file(p,"r")) == NULL)
339                                         {
340                                         perror(p);
341                                         goto end;
342                                         }
343                                 if ((ec_params = EC_KEY_new()) == NULL)
344                                         goto end;
345                                 if ((ec_params->group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL)) == NULL)
346                                         {
347                                         if (ec_params)
348                                                 EC_KEY_free(ec_params);
349                                         ERR_clear_error();
350                                         (void)BIO_reset(in);
351                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL,NULL)) == NULL)
352                                                 {       
353                                                 BIO_printf(bio_err,"unable to load EC parameters from file\n");
354                                                 goto end;
355                                                 }
356
357                                         if ((dtmp=X509_get_pubkey(xtmp)) == NULL) goto end;
358                                         if (dtmp->type == EVP_PKEY_EC)
359                                                 ec_params = ECParameters_dup(dtmp->pkey.eckey);
360                                         EVP_PKEY_free(dtmp);
361                                         X509_free(xtmp);
362                                         if (ec_params == NULL)
363                                                 {
364                                                 BIO_printf(bio_err,"Certificate does not contain EC parameters\n");
365                                                 goto end;
366                                                 }
367                                         }
368
369                                 BIO_free(in);
370                                 in=NULL;
371                                 
372                                 newkey = EC_GROUP_get_degree(ec_params->group);
373
374                                 }
375                         else
376 #endif
377 #ifndef OPENSSL_NO_DH
378                                 if (strncmp("dh:",p,4) == 0)
379                                 {
380                                 pkey_type=TYPE_DH;
381                                 p+=3;
382                                 }
383                         else
384 #endif
385                                 pkey_type=TYPE_RSA;
386
387                         newreq=1;
388                         }
389                 else if (strcmp(*argv,"-batch") == 0)
390                         batch=1;
391                 else if (strcmp(*argv,"-newhdr") == 0)
392                         newhdr=1;
393                 else if (strcmp(*argv,"-modulus") == 0)
394                         modulus=1;
395                 else if (strcmp(*argv,"-verify") == 0)
396                         verify=1;
397                 else if (strcmp(*argv,"-nodes") == 0)
398                         nodes=1;
399                 else if (strcmp(*argv,"-noout") == 0)
400                         noout=1;
401                 else if (strcmp(*argv,"-verbose") == 0)
402                         verbose=1;
403                 else if (strcmp(*argv,"-utf8") == 0)
404                         chtype = MBSTRING_UTF8;
405                 else if (strcmp(*argv,"-nameopt") == 0)
406                         {
407                         if (--argc < 1) goto bad;
408                         if (!set_name_ex(&nmflag, *(++argv))) goto bad;
409                         }
410                 else if (strcmp(*argv,"-subject") == 0)
411                         subject=1;
412                 else if (strcmp(*argv,"-text") == 0)
413                         text=1;
414                 else if (strcmp(*argv,"-x509") == 0)
415                         x509=1;
416                 else if (strcmp(*argv,"-asn1-kludge") == 0)
417                         kludge=1;
418                 else if (strcmp(*argv,"-no-asn1-kludge") == 0)
419                         kludge=0;
420                 else if (strcmp(*argv,"-subj") == 0)
421                         {
422                         if (--argc < 1) goto bad;
423                         subj= *(++argv);
424                         }
425                 else if (strcmp(*argv,"-days") == 0)
426                         {
427                         if (--argc < 1) goto bad;
428                         days= atoi(*(++argv));
429                         if (days == 0) days=30;
430                         }
431                 else if (strcmp(*argv,"-set_serial") == 0)
432                         {
433                         if (--argc < 1) goto bad;
434                         serial = s2i_ASN1_INTEGER(NULL, *(++argv));
435                         if (!serial) goto bad;
436                         }
437                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
438                         {
439                         /* ok */
440                         digest=md_alg;
441                         }
442                 else if (strcmp(*argv,"-extensions") == 0)
443                         {
444                         if (--argc < 1) goto bad;
445                         extensions = *(++argv);
446                         }
447                 else if (strcmp(*argv,"-reqexts") == 0)
448                         {
449                         if (--argc < 1) goto bad;
450                         req_exts = *(++argv);
451                         }
452                 else
453                         {
454                         BIO_printf(bio_err,"unknown option %s\n",*argv);
455                         badops=1;
456                         break;
457                         }
458                 argc--;
459                 argv++;
460                 }
461
462         if (badops)
463                 {
464 bad:
465                 BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
466                 BIO_printf(bio_err,"where options  are\n");
467                 BIO_printf(bio_err," -inform arg    input format - DER or PEM\n");
468                 BIO_printf(bio_err," -outform arg   output format - DER or PEM\n");
469                 BIO_printf(bio_err," -in arg        input file\n");
470                 BIO_printf(bio_err," -out arg       output file\n");
471                 BIO_printf(bio_err," -text          text form of request\n");
472                 BIO_printf(bio_err," -pubkey        output public key\n");
473                 BIO_printf(bio_err," -noout         do not output REQ\n");
474                 BIO_printf(bio_err," -verify        verify signature on REQ\n");
475                 BIO_printf(bio_err," -modulus       RSA modulus\n");
476                 BIO_printf(bio_err," -nodes         don't encrypt the output key\n");
477                 BIO_printf(bio_err," -engine e      use engine e, possibly a hardware device\n");
478                 BIO_printf(bio_err," -subject       output the request's subject\n");
479                 BIO_printf(bio_err," -passin        private key password source\n");
480                 BIO_printf(bio_err," -key file      use the private key contained in file\n");
481                 BIO_printf(bio_err," -keyform arg   key file format\n");
482                 BIO_printf(bio_err," -keyout arg    file to send the key to\n");
483                 BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
484                 BIO_printf(bio_err,"                load the file (or the files in the directory) into\n");
485                 BIO_printf(bio_err,"                the random number generator\n");
486                 BIO_printf(bio_err," -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
487                 BIO_printf(bio_err," -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
488                 BIO_printf(bio_err," -newkey ecdsa:file generate a new ECDSA key, parameters taken from CA in 'file'\n");
489                 BIO_printf(bio_err," -[digest]      Digest to sign with (md5, sha1, md2, mdc2, md4)\n");
490                 BIO_printf(bio_err," -config file   request template file.\n");
491                 BIO_printf(bio_err," -subj arg      set or modify request subject\n");
492                 BIO_printf(bio_err," -new           new request.\n");
493                 BIO_printf(bio_err," -batch         do not ask anything during request generation\n");
494                 BIO_printf(bio_err," -x509          output a x509 structure instead of a cert. req.\n");
495                 BIO_printf(bio_err," -days          number of days a certificate generated by -x509 is valid for.\n");
496                 BIO_printf(bio_err," -set_serial    serial number to use for a certificate generated by -x509.\n");
497                 BIO_printf(bio_err," -newhdr        output \"NEW\" in the header lines\n");
498                 BIO_printf(bio_err," -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
499                 BIO_printf(bio_err,"                have been reported as requiring\n");
500                 BIO_printf(bio_err," -extensions .. specify certificate extension section (override value in config file)\n");
501                 BIO_printf(bio_err," -reqexts ..    specify request extension section (override value in config file)\n");
502                 BIO_printf(bio_err," -utf8          input characters are UTF8 (default ASCII)\n");
503                 BIO_printf(bio_err," -nameopt arg    - various certificate name options\n");
504                 goto end;
505                 }
506
507         ERR_load_crypto_strings();
508         if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
509                 BIO_printf(bio_err, "Error getting passwords\n");
510                 goto end;
511         }
512
513 #ifndef MONOLITH /* else this has happened in openssl.c (global `config') */
514         /* Lets load up our environment a little */
515         p=getenv("OPENSSL_CONF");
516         if (p == NULL)
517                 p=getenv("SSLEAY_CONF");
518         if (p == NULL)
519                 {
520                 strcpy(config_name,X509_get_default_cert_area());
521 #ifndef OPENSSL_SYS_VMS
522                 strcat(config_name,"/");
523 #endif
524                 strcat(config_name,OPENSSL_CONF);
525                 p=config_name;
526                 }
527         default_config_file=p;
528         config=NCONF_new(NULL);
529         i=NCONF_load(config, p, &errline);
530 #endif
531
532         if (template != NULL)
533                 {
534                 long errline;
535
536                 if( verbose )
537                         BIO_printf(bio_err,"Using configuration from %s\n",template);
538                 req_conf=NCONF_new(NULL);
539                 i=NCONF_load(req_conf,template,&errline);
540                 if (i == 0)
541                         {
542                         BIO_printf(bio_err,"error on line %ld of %s\n",errline,template);
543                         goto end;
544                         }
545                 }
546         else
547                 {
548                 req_conf=config;
549                 if( verbose )
550                         BIO_printf(bio_err,"Using configuration from %s\n",
551                         default_config_file);
552                 if (req_conf == NULL)
553                         {
554                         BIO_printf(bio_err,"Unable to load config info\n");
555                         }
556                 }
557
558         if (req_conf != NULL)
559                 {
560                 if (!load_config(bio_err, req_conf))
561                         goto end;
562                 p=NCONF_get_string(req_conf,NULL,"oid_file");
563                 if (p == NULL)
564                         ERR_clear_error();
565                 if (p != NULL)
566                         {
567                         BIO *oid_bio;
568
569                         oid_bio=BIO_new_file(p,"r");
570                         if (oid_bio == NULL) 
571                                 {
572                                 /*
573                                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
574                                 ERR_print_errors(bio_err);
575                                 */
576                                 }
577                         else
578                                 {
579                                 OBJ_create_objects(oid_bio);
580                                 BIO_free(oid_bio);
581                                 }
582                         }
583                 }
584         if(!add_oid_section(bio_err, req_conf)) goto end;
585
586         if (md_alg == NULL)
587                 {
588                 p=NCONF_get_string(req_conf,SECTION,"default_md");
589                 if (p == NULL)
590                         ERR_clear_error();
591                 if (p != NULL)
592                         {
593                         if ((md_alg=EVP_get_digestbyname(p)) != NULL)
594                                 digest=md_alg;
595                         }
596                 }
597
598         if (!extensions)
599                 {
600                 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
601                 if (!extensions)
602                         ERR_clear_error();
603                 }
604         if (extensions) {
605                 /* Check syntax of file */
606                 X509V3_CTX ctx;
607                 X509V3_set_ctx_test(&ctx);
608                 X509V3_set_nconf(&ctx, req_conf);
609                 if(!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
610                         BIO_printf(bio_err,
611                          "Error Loading extension section %s\n", extensions);
612                         goto end;
613                 }
614         }
615
616         if(!passin)
617                 {
618                 passin = NCONF_get_string(req_conf, SECTION, "input_password");
619                 if (!passin)
620                         ERR_clear_error();
621                 }
622         
623         if(!passout)
624                 {
625                 passout = NCONF_get_string(req_conf, SECTION, "output_password");
626                 if (!passout)
627                         ERR_clear_error();
628                 }
629
630         p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
631         if (!p)
632                 ERR_clear_error();
633
634         if(p && !ASN1_STRING_set_default_mask_asc(p)) {
635                 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
636                 goto end;
637         }
638
639         if (chtype != MBSTRING_UTF8)
640                 {
641                 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
642                 if (!p)
643                         ERR_clear_error();
644                 else if (!strcmp(p, "yes"))
645                         chtype = MBSTRING_UTF8;
646                 }
647
648
649         if(!req_exts)
650                 {
651                 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
652                 if (!req_exts)
653                         ERR_clear_error();
654                 }
655         if(req_exts) {
656                 /* Check syntax of file */
657                 X509V3_CTX ctx;
658                 X509V3_set_ctx_test(&ctx);
659                 X509V3_set_nconf(&ctx, req_conf);
660                 if(!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
661                         BIO_printf(bio_err,
662                          "Error Loading request extension section %s\n",
663                                                                 req_exts);
664                         goto end;
665                 }
666         }
667
668         in=BIO_new(BIO_s_file());
669         out=BIO_new(BIO_s_file());
670         if ((in == NULL) || (out == NULL))
671                 goto end;
672
673         e = setup_engine(bio_err, engine, 0);
674
675         if (keyfile != NULL)
676                 {
677                 pkey = load_key(bio_err, keyfile, keyform, 0, passin, e,
678                         "Private Key");
679                 if (!pkey)
680                         {
681                         /* load_key() has already printed an appropriate
682                            message */
683                         goto end;
684                         }
685                 if (EVP_PKEY_type(pkey->type) == EVP_PKEY_DSA || 
686                         EVP_PKEY_type(pkey->type) == EVP_PKEY_EC)
687                         {
688                         char *randfile = NCONF_get_string(req_conf,SECTION,"RANDFILE");
689                         if (randfile == NULL)
690                                 ERR_clear_error();
691                         app_RAND_load_file(randfile, bio_err, 0);
692                         }
693                 }
694
695         if (newreq && (pkey == NULL))
696                 {
697                 char *randfile = NCONF_get_string(req_conf,SECTION,"RANDFILE");
698                 if (randfile == NULL)
699                         ERR_clear_error();
700                 app_RAND_load_file(randfile, bio_err, 0);
701                 if (inrand)
702                         app_RAND_load_files(inrand);
703         
704                 if (newkey <= 0)
705                         {
706                         if (!NCONF_get_number(req_conf,SECTION,BITS, &newkey))
707                                 newkey=DEFAULT_KEY_LENGTH;
708                         }
709
710                 if (newkey < MIN_KEY_LENGTH && (pkey_type == TYPE_RSA || pkey_type == TYPE_DSA))
711                 /* TODO: appropriate minimal keylength for the different algorithm (esp. ECDSA) */
712                         {
713                         BIO_printf(bio_err,"private key length is too short,\n");
714                         BIO_printf(bio_err,"it needs to be at least %d bits, not %d\n",MIN_KEY_LENGTH,newkey);
715                         goto end;
716                         }
717                 BIO_printf(bio_err,"Generating a %d bit %s private key\n",
718                         newkey,(pkey_type == TYPE_RSA)?"RSA":(pkey_type == TYPE_DSA)?"DSA":"ECDSA");
719
720                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
721
722 #ifndef OPENSSL_NO_RSA
723                 if (pkey_type == TYPE_RSA)
724                         {
725                         if (!EVP_PKEY_assign_RSA(pkey,
726                                 RSA_generate_key(newkey,0x10001,
727                                         req_cb,bio_err)))
728                                 goto end;
729                         }
730                 else
731 #endif
732 #ifndef OPENSSL_NO_DSA
733                         if (pkey_type == TYPE_DSA)
734                         {
735                         if (!DSA_generate_key(dsa_params)) goto end;
736                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
737                         dsa_params=NULL;
738                         }
739 #endif
740 #ifndef OPENSSL_NO_EC
741                         if (pkey_type == TYPE_EC)
742                         {
743                         if (!EC_KEY_generate_key(ec_params)) goto end;
744                         if (!EVP_PKEY_assign_EC_KEY(pkey, ec_params)) 
745                                 goto end;
746                         ec_params = NULL;
747                         }
748 #endif
749
750                 app_RAND_write_file(randfile, bio_err);
751
752                 if (pkey == NULL) goto end;
753
754                 if (keyout == NULL)
755                         {
756                         keyout=NCONF_get_string(req_conf,SECTION,KEYFILE);
757                         if (keyout == NULL)
758                                 ERR_clear_error();
759                         }
760                 
761                 if (keyout == NULL)
762                         {
763                         BIO_printf(bio_err,"writing new private key to stdout\n");
764                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
765 #ifdef OPENSSL_SYS_VMS
766                         {
767                         BIO *tmpbio = BIO_new(BIO_f_linebuffer());
768                         out = BIO_push(tmpbio, out);
769                         }
770 #endif
771                         }
772                 else
773                         {
774                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
775                         if (BIO_write_filename(out,keyout) <= 0)
776                                 {
777                                 perror(keyout);
778                                 goto end;
779                                 }
780                         }
781
782                 p=NCONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
783                 if (p == NULL)
784                         {
785                         ERR_clear_error();
786                         p=NCONF_get_string(req_conf,SECTION,"encrypt_key");
787                         if (p == NULL)
788                                 ERR_clear_error();
789                         }
790                 if ((p != NULL) && (strcmp(p,"no") == 0))
791                         cipher=NULL;
792                 if (nodes) cipher=NULL;
793                 
794                 i=0;
795 loop:
796                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
797                         NULL,0,NULL,passout))
798                         {
799                         if ((ERR_GET_REASON(ERR_peek_error()) ==
800                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
801                                 {
802                                 ERR_clear_error();
803                                 i++;
804                                 goto loop;
805                                 }
806                         goto end;
807                         }
808                 BIO_printf(bio_err,"-----\n");
809                 }
810
811         if (!newreq)
812                 {
813                 /* Since we are using a pre-existing certificate
814                  * request, the kludge 'format' info should not be
815                  * changed. */
816                 kludge= -1;
817                 if (infile == NULL)
818                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
819                 else
820                         {
821                         if (BIO_read_filename(in,infile) <= 0)
822                                 {
823                                 perror(infile);
824                                 goto end;
825                                 }
826                         }
827
828                 if      (informat == FORMAT_ASN1)
829                         req=d2i_X509_REQ_bio(in,NULL);
830                 else if (informat == FORMAT_PEM)
831                         req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
832                 else
833                         {
834                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
835                         goto end;
836                         }
837                 if (req == NULL)
838                         {
839                         BIO_printf(bio_err,"unable to load X509 request\n");
840                         goto end;
841                         }
842                 }
843
844         if (newreq || x509)
845                 {
846                 if (pkey == NULL)
847                         {
848                         BIO_printf(bio_err,"you need to specify a private key\n");
849                         goto end;
850                         }
851 #ifndef OPENSSL_NO_DSA
852                 if (pkey->type == EVP_PKEY_DSA)
853                         digest=EVP_dss1();
854 #endif
855 #ifndef OPENSSL_NO_ECDSA
856                 if (pkey->type == EVP_PKEY_EC)
857                         digest=EVP_ecdsa();
858 #endif
859                 if (req == NULL)
860                         {
861                         req=X509_REQ_new();
862                         if (req == NULL)
863                                 {
864                                 goto end;
865                                 }
866
867                         i=make_REQ(req,pkey,subj,!x509, chtype);
868                         subj=NULL; /* done processing '-subj' option */
869                         if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes))
870                                 {
871                                 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
872                                 req->req_info->attributes = NULL;
873                                 }
874                         if (!i)
875                                 {
876                                 BIO_printf(bio_err,"problems making Certificate Request\n");
877                                 goto end;
878                                 }
879                         }
880                 if (x509)
881                         {
882                         EVP_PKEY *tmppkey;
883                         X509V3_CTX ext_ctx;
884                         if ((x509ss=X509_new()) == NULL) goto end;
885
886                         /* Set version to V3 */
887                         if(!X509_set_version(x509ss, 2)) goto end;
888                         if (serial)
889                                 {
890                                 if (!X509_set_serialNumber(x509ss, serial)) goto end;
891                                 }
892                         else
893                                 {
894                                 if (!ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L)) goto end;
895                                 }
896
897                         if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
898                         if (!X509_gmtime_adj(X509_get_notBefore(x509ss),0)) goto end;
899                         if (!X509_gmtime_adj(X509_get_notAfter(x509ss), (long)60*60*24*days)) goto end;
900                         if (!X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
901                         tmppkey = X509_REQ_get_pubkey(req);
902                         if (!tmppkey || !X509_set_pubkey(x509ss,tmppkey)) goto end;
903                         EVP_PKEY_free(tmppkey);
904
905                         /* Set up V3 context struct */
906
907                         X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
908                         X509V3_set_nconf(&ext_ctx, req_conf);
909
910                         /* Add extensions */
911                         if(extensions && !X509V3_EXT_add_nconf(req_conf, 
912                                         &ext_ctx, extensions, x509ss))
913                                 {
914                                 BIO_printf(bio_err,
915                                         "Error Loading extension section %s\n",
916                                         extensions);
917                                 goto end;
918                                 }
919                         
920                         if (!(i=X509_sign(x509ss,pkey,digest)))
921                                 goto end;
922                         }
923                 else
924                         {
925                         X509V3_CTX ext_ctx;
926
927                         /* Set up V3 context struct */
928
929                         X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
930                         X509V3_set_nconf(&ext_ctx, req_conf);
931
932                         /* Add extensions */
933                         if(req_exts && !X509V3_EXT_REQ_add_nconf(req_conf, 
934                                         &ext_ctx, req_exts, req))
935                                 {
936                                 BIO_printf(bio_err,
937                                         "Error Loading extension section %s\n",
938                                         req_exts);
939                                 goto end;
940                                 }
941                         if (!(i=X509_REQ_sign(req,pkey,digest)))
942                                 goto end;
943                         }
944                 }
945
946         if (subj && x509)
947                 {
948                 BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
949                 goto end;
950                 }
951
952         if (subj && !x509)
953                 {
954                 if (verbose)
955                         {
956                         BIO_printf(bio_err, "Modifying Request's Subject\n");
957                         print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag);
958                         }
959
960                 if (build_subject(req, subj, chtype) == 0)
961                         {
962                         BIO_printf(bio_err, "ERROR: cannot modify subject\n");
963                         ex=1;
964                         goto end;
965                         }
966
967                 req->req_info->enc.modified = 1;
968
969                 if (verbose)
970                         {
971                         print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag);
972                         }
973                 }
974
975         if (verify && !x509)
976                 {
977                 int tmp=0;
978
979                 if (pkey == NULL)
980                         {
981                         pkey=X509_REQ_get_pubkey(req);
982                         tmp=1;
983                         if (pkey == NULL) goto end;
984                         }
985
986                 i=X509_REQ_verify(req,pkey);
987                 if (tmp) {
988                         EVP_PKEY_free(pkey);
989                         pkey=NULL;
990                 }
991
992                 if (i < 0)
993                         {
994                         goto end;
995                         }
996                 else if (i == 0)
997                         {
998                         BIO_printf(bio_err,"verify failure\n");
999                         ERR_print_errors(bio_err);
1000                         }
1001                 else /* if (i > 0) */
1002                         BIO_printf(bio_err,"verify OK\n");
1003                 }
1004
1005         if (noout && !text && !modulus && !subject && !pubkey)
1006                 {
1007                 ex=0;
1008                 goto end;
1009                 }
1010
1011         if (outfile == NULL)
1012                 {
1013                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
1014 #ifdef OPENSSL_SYS_VMS
1015                 {
1016                 BIO *tmpbio = BIO_new(BIO_f_linebuffer());
1017                 out = BIO_push(tmpbio, out);
1018                 }
1019 #endif
1020                 }
1021         else
1022                 {
1023                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
1024                         i=(int)BIO_append_filename(out,outfile);
1025                 else
1026                         i=(int)BIO_write_filename(out,outfile);
1027                 if (!i)
1028                         {
1029                         perror(outfile);
1030                         goto end;
1031                         }
1032                 }
1033
1034         if (pubkey)
1035                 {
1036                 EVP_PKEY *tpubkey; 
1037                 tpubkey=X509_REQ_get_pubkey(req);
1038                 if (tpubkey == NULL)
1039                         {
1040                         BIO_printf(bio_err,"Error getting public key\n");
1041                         ERR_print_errors(bio_err);
1042                         goto end;
1043                         }
1044                 PEM_write_bio_PUBKEY(out, tpubkey);
1045                 EVP_PKEY_free(tpubkey);
1046                 }
1047
1048         if (text)
1049                 {
1050                 if (x509)
1051                         X509_print(out,x509ss);
1052                 else    
1053                         X509_REQ_print(out,req);
1054                 }
1055
1056         if(subject) 
1057                 {
1058                 if(x509)
1059                         print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag);
1060                 else
1061                         print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag);
1062                 }
1063
1064         if (modulus)
1065                 {
1066                 EVP_PKEY *tpubkey;
1067
1068                 if (x509)
1069                         tpubkey=X509_get_pubkey(x509ss);
1070                 else
1071                         tpubkey=X509_REQ_get_pubkey(req);
1072                 if (tpubkey == NULL)
1073                         {
1074                         fprintf(stdout,"Modulus=unavailable\n");
1075                         goto end; 
1076                         }
1077                 fprintf(stdout,"Modulus=");
1078 #ifndef OPENSSL_NO_RSA
1079                 if (tpubkey->type == EVP_PKEY_RSA)
1080                         BN_print(out,tpubkey->pkey.rsa->n);
1081                 else
1082 #endif
1083                         fprintf(stdout,"Wrong Algorithm type");
1084                 EVP_PKEY_free(tpubkey);
1085                 fprintf(stdout,"\n");
1086                 }
1087
1088         if (!noout && !x509)
1089                 {
1090                 if      (outformat == FORMAT_ASN1)
1091                         i=i2d_X509_REQ_bio(out,req);
1092                 else if (outformat == FORMAT_PEM) {
1093                         if(newhdr) i=PEM_write_bio_X509_REQ_NEW(out,req);
1094                         else i=PEM_write_bio_X509_REQ(out,req);
1095                 } else {
1096                         BIO_printf(bio_err,"bad output format specified for outfile\n");
1097                         goto end;
1098                         }
1099                 if (!i)
1100                         {
1101                         BIO_printf(bio_err,"unable to write X509 request\n");
1102                         goto end;
1103                         }
1104                 }
1105         if (!noout && x509 && (x509ss != NULL))
1106                 {
1107                 if      (outformat == FORMAT_ASN1)
1108                         i=i2d_X509_bio(out,x509ss);
1109                 else if (outformat == FORMAT_PEM)
1110                         i=PEM_write_bio_X509(out,x509ss);
1111                 else    {
1112                         BIO_printf(bio_err,"bad output format specified for outfile\n");
1113                         goto end;
1114                         }
1115                 if (!i)
1116                         {
1117                         BIO_printf(bio_err,"unable to write X509 certificate\n");
1118                         goto end;
1119                         }
1120                 }
1121         ex=0;
1122 end:
1123         if (ex)
1124                 {
1125                 ERR_print_errors(bio_err);
1126                 }
1127         if ((req_conf != NULL) && (req_conf != config)) NCONF_free(req_conf);
1128         BIO_free(in);
1129         BIO_free_all(out);
1130         EVP_PKEY_free(pkey);
1131         X509_REQ_free(req);
1132         X509_free(x509ss);
1133         ASN1_INTEGER_free(serial);
1134         if(passargin && passin) OPENSSL_free(passin);
1135         if(passargout && passout) OPENSSL_free(passout);
1136         OBJ_cleanup();
1137 #ifndef OPENSSL_NO_DSA
1138         if (dsa_params != NULL) DSA_free(dsa_params);
1139 #endif
1140 #ifndef OPENSSL_NO_EC
1141         if (ec_params != NULL) EC_KEY_free(ec_params);
1142 #endif
1143         apps_shutdown();
1144         EXIT(ex);
1145         }
1146
1147 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int attribs,
1148                         unsigned long chtype)
1149         {
1150         int ret=0,i;
1151         char no_prompt = 0;
1152         STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1153         char *tmp, *dn_sect,*attr_sect;
1154
1155         tmp=NCONF_get_string(req_conf,SECTION,PROMPT);
1156         if (tmp == NULL)
1157                 ERR_clear_error();
1158         if((tmp != NULL) && !strcmp(tmp, "no")) no_prompt = 1;
1159
1160         dn_sect=NCONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
1161         if (dn_sect == NULL)
1162                 {
1163                 BIO_printf(bio_err,"unable to find '%s' in config\n",
1164                         DISTINGUISHED_NAME);
1165                 goto err;
1166                 }
1167         dn_sk=NCONF_get_section(req_conf,dn_sect);
1168         if (dn_sk == NULL)
1169                 {
1170                 BIO_printf(bio_err,"unable to get '%s' section\n",dn_sect);
1171                 goto err;
1172                 }
1173
1174         attr_sect=NCONF_get_string(req_conf,SECTION,ATTRIBUTES);
1175         if (attr_sect == NULL)
1176                 {
1177                 ERR_clear_error();              
1178                 attr_sk=NULL;
1179                 }
1180         else
1181                 {
1182                 attr_sk=NCONF_get_section(req_conf,attr_sect);
1183                 if (attr_sk == NULL)
1184                         {
1185                         BIO_printf(bio_err,"unable to get '%s' section\n",attr_sect);
1186                         goto err;
1187                         }
1188                 }
1189
1190         /* setup version number */
1191         if (!X509_REQ_set_version(req,0L)) goto err; /* version 1 */
1192
1193         if (no_prompt) 
1194                 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1195         else 
1196                 {
1197                 if (subj)
1198                         i = build_subject(req, subj, chtype);
1199                 else
1200                         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype);
1201                 }
1202         if(!i) goto err;
1203
1204         if (!X509_REQ_set_pubkey(req,pkey)) goto err;
1205
1206         ret=1;
1207 err:
1208         return(ret);
1209         }
1210
1211 /*
1212  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1213  * where characters may be escaped by \
1214  */
1215 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype)
1216         {
1217         X509_NAME *n;
1218
1219         if (!(n = do_subject(subject, chtype)))
1220                 return 0;
1221
1222         if (!X509_REQ_set_subject_name(req, n))
1223                 {
1224                 X509_NAME_free(n);
1225                 return 0;
1226                 }
1227         X509_NAME_free(n);
1228         return 1;
1229 }
1230
1231
1232 static int prompt_info(X509_REQ *req,
1233                 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
1234                 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
1235                 unsigned long chtype)
1236         {
1237         int i;
1238         char *p,*q;
1239         char buf[100];
1240         int nid;
1241         long n_min,n_max;
1242         char *type,*def,*value;
1243         CONF_VALUE *v;
1244         X509_NAME *subj;
1245         subj = X509_REQ_get_subject_name(req);
1246
1247         if(!batch)
1248                 {
1249                 BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
1250                 BIO_printf(bio_err,"into your certificate request.\n");
1251                 BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
1252                 BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
1253                 BIO_printf(bio_err,"For some fields there will be a default value,\n");
1254                 BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
1255                 BIO_printf(bio_err,"-----\n");
1256                 }
1257
1258
1259         if (sk_CONF_VALUE_num(dn_sk))
1260                 {
1261                 i= -1;
1262 start:          for (;;)
1263                         {
1264                         i++;
1265                         if (sk_CONF_VALUE_num(dn_sk) <= i) break;
1266
1267                         v=sk_CONF_VALUE_value(dn_sk,i);
1268                         p=q=NULL;
1269                         type=v->name;
1270                         if(!check_end(type,"_min") || !check_end(type,"_max") ||
1271                                 !check_end(type,"_default") ||
1272                                          !check_end(type,"_value")) continue;
1273                         /* Skip past any leading X. X: X, etc to allow for
1274                          * multiple instances 
1275                          */
1276                         for(p = v->name; *p ; p++) 
1277                                 if ((*p == ':') || (*p == ',') ||
1278                                                          (*p == '.')) {
1279                                         p++;
1280                                         if(*p) type = p;
1281                                         break;
1282                                 }
1283                         /* If OBJ not recognised ignore it */
1284                         if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
1285                         sprintf(buf,"%s_default",v->name);
1286                         if ((def=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1287                                 {
1288                                 ERR_clear_error();
1289                                 def="";
1290                                 }
1291                                 
1292                         sprintf(buf,"%s_value",v->name);
1293                         if ((value=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1294                                 {
1295                                 ERR_clear_error();
1296                                 value=NULL;
1297                                 }
1298
1299                         sprintf(buf,"%s_min",v->name);
1300                         if (!NCONF_get_number(req_conf,dn_sect,buf, &n_min))
1301                                 n_min = -1;
1302
1303                         sprintf(buf,"%s_max",v->name);
1304                         if (!NCONF_get_number(req_conf,dn_sect,buf, &n_max))
1305                                 n_max = -1;
1306
1307                         if (!add_DN_object(subj,v->value,def,value,nid,
1308                                 n_min,n_max, chtype))
1309                                 return 0;
1310                         }
1311                 if (X509_NAME_entry_count(subj) == 0)
1312                         {
1313                         BIO_printf(bio_err,"error, no objects specified in config file\n");
1314                         return 0;
1315                         }
1316
1317                 if (attribs)
1318                         {
1319                         if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch))
1320                                 {
1321                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
1322                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
1323                                 }
1324
1325                         i= -1;
1326 start2:                 for (;;)
1327                                 {
1328                                 i++;
1329                                 if ((attr_sk == NULL) ||
1330                                             (sk_CONF_VALUE_num(attr_sk) <= i))
1331                                         break;
1332
1333                                 v=sk_CONF_VALUE_value(attr_sk,i);
1334                                 type=v->name;
1335                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
1336                                         goto start2;
1337
1338                                 sprintf(buf,"%s_default",type);
1339                                 if ((def=NCONF_get_string(req_conf,attr_sect,buf))
1340                                         == NULL)
1341                                         {
1342                                         ERR_clear_error();
1343                                         def="";
1344                                         }
1345                                 
1346                                 
1347                                 sprintf(buf,"%s_value",type);
1348                                 if ((value=NCONF_get_string(req_conf,attr_sect,buf))
1349                                         == NULL)
1350                                         {
1351                                         ERR_clear_error();
1352                                         value=NULL;
1353                                         }
1354
1355                                 sprintf(buf,"%s_min",type);
1356                                 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_min))
1357                                         n_min = -1;
1358
1359                                 sprintf(buf,"%s_max",type);
1360                                 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_max))
1361                                         n_max = -1;
1362
1363                                 if (!add_attribute_object(req,
1364                                         v->value,def,value,nid,n_min,n_max, chtype))
1365                                         return 0;
1366                                 }
1367                         }
1368                 }
1369         else
1370                 {
1371                 BIO_printf(bio_err,"No template, please set one up.\n");
1372                 return 0;
1373                 }
1374
1375         return 1;
1376
1377         }
1378
1379 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1380                         STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype)
1381         {
1382         int i;
1383         char *p,*q;
1384         char *type;
1385         CONF_VALUE *v;
1386         X509_NAME *subj;
1387
1388         subj = X509_REQ_get_subject_name(req);
1389
1390         for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++)
1391                 {
1392                 v=sk_CONF_VALUE_value(dn_sk,i);
1393                 p=q=NULL;
1394                 type=v->name;
1395                 /* Skip past any leading X. X: X, etc to allow for
1396                  * multiple instances 
1397                  */
1398                 for(p = v->name; *p ; p++) 
1399 #ifndef CHARSET_EBCDIC
1400                         if ((*p == ':') || (*p == ',') || (*p == '.')) {
1401 #else
1402                         if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.'])) {
1403 #endif
1404                                 p++;
1405                                 if(*p) type = p;
1406                                 break;
1407                         }
1408                 if (!X509_NAME_add_entry_by_txt(subj,type, chtype,
1409                                 (unsigned char *) v->value,-1,-1,0)) return 0;
1410
1411                 }
1412
1413                 if (!X509_NAME_entry_count(subj))
1414                         {
1415                         BIO_printf(bio_err,"error, no objects specified in config file\n");
1416                         return 0;
1417                         }
1418                 if (attribs)
1419                         {
1420                         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++)
1421                                 {
1422                                 v=sk_CONF_VALUE_value(attr_sk,i);
1423                                 if(!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1424                                         (unsigned char *)v->value, -1)) return 0;
1425                                 }
1426                         }
1427         return 1;
1428         }
1429
1430
1431 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
1432              int nid, int n_min, int n_max, unsigned long chtype)
1433         {
1434         int i,ret=0;
1435         MS_STATIC char buf[1024];
1436 start:
1437         if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1438         (void)BIO_flush(bio_err);
1439         if(value != NULL)
1440                 {
1441                 strcpy(buf,value);
1442                 strcat(buf,"\n");
1443                 BIO_printf(bio_err,"%s\n",value);
1444                 }
1445         else
1446                 {
1447                 buf[0]='\0';
1448                 if (!batch)
1449                         {
1450                         fgets(buf,1024,stdin);
1451                         }
1452                 else
1453                         {
1454                         buf[0] = '\n';
1455                         buf[1] = '\0';
1456                         }
1457                 }
1458
1459         if (buf[0] == '\0') return(0);
1460         else if (buf[0] == '\n')
1461                 {
1462                 if ((def == NULL) || (def[0] == '\0'))
1463                         return(1);
1464                 strcpy(buf,def);
1465                 strcat(buf,"\n");
1466                 }
1467         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1468
1469         i=strlen(buf);
1470         if (buf[i-1] != '\n')
1471                 {
1472                 BIO_printf(bio_err,"weird input :-(\n");
1473                 return(0);
1474                 }
1475         buf[--i]='\0';
1476 #ifdef CHARSET_EBCDIC
1477         ebcdic2ascii(buf, buf, i);
1478 #endif
1479         if(!req_check_len(i, n_min, n_max)) goto start;
1480         if (!X509_NAME_add_entry_by_NID(n,nid, chtype,
1481                                 (unsigned char *) buf, -1,-1,0)) goto err;
1482         ret=1;
1483 err:
1484         return(ret);
1485         }
1486
1487 static int add_attribute_object(X509_REQ *req, char *text,
1488                                 char *def, char *value, int nid, int n_min,
1489                                 int n_max, unsigned long chtype)
1490         {
1491         int i;
1492         static char buf[1024];
1493
1494 start:
1495         if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1496         (void)BIO_flush(bio_err);
1497         if (value != NULL)
1498                 {
1499                 strcpy(buf,value);
1500                 strcat(buf,"\n");
1501                 BIO_printf(bio_err,"%s\n",value);
1502                 }
1503         else
1504                 {
1505                 buf[0]='\0';
1506                 if (!batch)
1507                         {
1508                         fgets(buf,1024,stdin);
1509                         }
1510                 else
1511                         {
1512                         buf[0] = '\n';
1513                         buf[1] = '\0';
1514                         }
1515                 }
1516
1517         if (buf[0] == '\0') return(0);
1518         else if (buf[0] == '\n')
1519                 {
1520                 if ((def == NULL) || (def[0] == '\0'))
1521                         return(1);
1522                 strcpy(buf,def);
1523                 strcat(buf,"\n");
1524                 }
1525         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1526
1527         i=strlen(buf);
1528         if (buf[i-1] != '\n')
1529                 {
1530                 BIO_printf(bio_err,"weird input :-(\n");
1531                 return(0);
1532                 }
1533         buf[--i]='\0';
1534 #ifdef CHARSET_EBCDIC
1535         ebcdic2ascii(buf, buf, i);
1536 #endif
1537         if(!req_check_len(i, n_min, n_max)) goto start;
1538
1539         if(!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1540                                         (unsigned char *)buf, -1)) {
1541                 BIO_printf(bio_err, "Error adding attribute\n");
1542                 ERR_print_errors(bio_err);
1543                 goto err;
1544         }
1545
1546         return(1);
1547 err:
1548         return(0);
1549         }
1550
1551 #ifndef OPENSSL_NO_RSA
1552 static void MS_CALLBACK req_cb(int p, int n, void *arg)
1553         {
1554         char c='*';
1555
1556         if (p == 0) c='.';
1557         if (p == 1) c='+';
1558         if (p == 2) c='*';
1559         if (p == 3) c='\n';
1560         BIO_write((BIO *)arg,&c,1);
1561         (void)BIO_flush((BIO *)arg);
1562 #ifdef LINT
1563         p=n;
1564 #endif
1565         }
1566 #endif
1567
1568 static int req_check_len(int len, int n_min, int n_max)
1569         {
1570         if ((n_min > 0) && (len < n_min))
1571                 {
1572                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",n_min);
1573                 return(0);
1574                 }
1575         if ((n_max >= 0) && (len > n_max))
1576                 {
1577                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",n_max);
1578                 return(0);
1579                 }
1580         return(1);
1581         }
1582
1583 /* Check if the end of a string matches 'end' */
1584 static int check_end(char *str, char *end)
1585 {
1586         int elen, slen; 
1587         char *tmp;
1588         elen = strlen(end);
1589         slen = strlen(str);
1590         if(elen > slen) return 1;
1591         tmp = str + slen - elen;
1592         return strcmp(tmp, end);
1593 }