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