RT2547: Tighten perms on generated privkey files
[openssl.git] / apps / req.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <time.h>
61 #include <string.h>
62 #include "apps.h"
63 #include <openssl/bio.h>
64 #include <openssl/evp.h>
65 #include <openssl/conf.h>
66 #include <openssl/err.h>
67 #include <openssl/asn1.h>
68 #include <openssl/x509.h>
69 #include <openssl/x509v3.h>
70 #include <openssl/objects.h>
71 #include <openssl/pem.h>
72 #include <openssl/bn.h>
73 #ifndef OPENSSL_NO_RSA
74 # include <openssl/rsa.h>
75 #endif
76 #ifndef OPENSSL_NO_DSA
77 # include <openssl/dsa.h>
78 #endif
79
80 #define SECTION         "req"
81
82 #define BITS            "default_bits"
83 #define KEYFILE         "default_keyfile"
84 #define PROMPT          "prompt"
85 #define DISTINGUISHED_NAME      "distinguished_name"
86 #define ATTRIBUTES      "attributes"
87 #define V3_EXTENSIONS   "x509_extensions"
88 #define REQ_EXTENSIONS  "req_extensions"
89 #define STRING_MASK     "string_mask"
90 #define UTF8_IN         "utf8"
91
92 #define DEFAULT_KEY_LENGTH      512
93 #define MIN_KEY_LENGTH          384
94
95 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
96                     int attribs, unsigned long chtype);
97 static int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
98                          int multirdn);
99 static int prompt_info(X509_REQ *req,
100                        STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
101                        STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
102                        int attribs, unsigned long chtype);
103 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
104                      STACK_OF(CONF_VALUE) *attr, int attribs,
105                      unsigned long chtype);
106 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
107                                 char *value, int nid, int n_min, int n_max,
108                                 unsigned long chtype);
109 static int add_DN_object(X509_NAME *n, char *text, const char *def,
110                          char *value, int nid, int n_min, int n_max,
111                          unsigned long chtype, int mval);
112 static int genpkey_cb(EVP_PKEY_CTX *ctx);
113 static int req_check_len(int len, int n_min, int n_max);
114 static int check_end(const char *str, const char *end);
115 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
116                                     int *pkey_type, long *pkeylen,
117                                     char **palgnam, ENGINE *keygen_engine);
118 static CONF *req_conf = NULL;
119 static int batch = 0;
120
121 typedef enum OPTION_choice {
122     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
123     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
124     OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
125     OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_RAND, OPT_NEWKEY,
126     OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
127     OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
128     OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
129     OPT_ASN1_KLUDGE, OPT_NO_ASN1_KLUDGE, OPT_MULTIVALUE_RDN,
130     OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS, OPT_REQEXTS, OPT_MD
131 } OPTION_CHOICE;
132
133 OPTIONS req_options[] = {
134     {"help", OPT_HELP, '-', "Display this summary"},
135     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
136     {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
137     {"in", OPT_IN, '<', "Input file"},
138     {"out", OPT_OUT, '>', "Output file"},
139     {"key", OPT_KEY, '<', "Use the private key contained in file"},
140     {"keyform", OPT_KEYFORM, 'F', "Key file format"},
141     {"pubkey", OPT_PUBKEY, '-', "Output public key"},
142     {"new", OPT_NEW, '-', "New request"},
143     {"config", OPT_CONFIG, '<', "Request template file"},
144     {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
145     {"passin", OPT_PASSIN, 's', "Private key password source"},
146     {"passout", OPT_PASSOUT, 's'},
147     {"rand", OPT_RAND, 's',
148      "Load the file(s) into the random number generator"},
149     {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
150     {"pkeyopt", OPT_PKEYOPT, 's'},
151     {"sigopt", OPT_SIGOPT, 's'},
152     {"batch", OPT_BATCH, '-',
153      "Do not ask anything during request generation"},
154     {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
155     {"modulus", OPT_MODULUS, '-', "RSA modulus"},
156     {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
157     {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
158     {"noout", OPT_NOOUT, '-', "Do not output REQ"},
159     {"verbose", OPT_VERBOSE, '-'},
160     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
161     {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
162     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
163     {"text", OPT_TEXT, '-', "Text form of request"},
164     {"x509", OPT_X509, '-',
165      "Output a x509 structure instead of a cert request"},
166     {"asn1-kludge", OPT_ASN1_KLUDGE, '-',
167      "Output the request in a format that is wrong"},
168     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
169     {"no-asn1-kludge", OPT_NO_ASN1_KLUDGE, '-'},
170     {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
171     {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
172     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
173      "Enable support for multivalued RDNs"},
174     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
175     {"set-serial", OPT_SET_SERIAL, 'p', "Serial number to use"},
176     {"extensions", OPT_EXTENSIONS, 's',
177      "Cert extension section (override value in config file)"},
178     {"reqexts", OPT_REQEXTS, 's',
179      "Request extension section (override value in config file)"},
180     {"", OPT_MD, '-', "Any supported digest"},
181 #ifndef OPENSSL_NO_ENGINE
182     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
183     {"keygen_engine", OPT_KEYGEN_ENGINE, 's'},
184 #endif
185     {NULL}
186 };
187
188 int req_main(int argc, char **argv)
189 {
190     ASN1_INTEGER *serial = NULL;
191     BIO *in = NULL, *out = NULL;
192     ENGINE *e = NULL, *gen_eng = NULL;
193     EVP_PKEY *pkey = NULL;
194     EVP_PKEY_CTX *genctx = NULL;
195     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
196     X509 *x509ss = NULL;
197     X509_REQ *req = NULL;
198     const EVP_CIPHER *cipher = NULL;
199     const EVP_MD *md_alg = NULL, *digest = NULL;
200     char *extensions = NULL, *infile = NULL;
201     char *outfile = NULL, *keyfile = NULL, *inrand = NULL;
202     char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
203     char *passin = NULL, *passout = NULL, *req_exts = NULL, *subj = NULL;
204     char *template = default_config_file, *keyout = NULL;
205     const char *keyalg = NULL;
206     OPTION_CHOICE o;
207     int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0;
208     int pkey_type = -1, private = 0;
209     int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
210     int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
211     int nodes = 0, kludge = 0, newhdr = 0, subject = 0, pubkey = 0;
212     long newkey = -1;
213     unsigned long chtype = MBSTRING_ASC, nmflag = 0, reqflag = 0;
214
215 #ifndef OPENSSL_NO_DES
216     cipher = EVP_des_ede3_cbc();
217 #endif
218
219     prog = opt_init(argc, argv, req_options);
220     while ((o = opt_next()) != OPT_EOF) {
221         switch (o) {
222         case OPT_EOF:
223         case OPT_ERR:
224  opthelp:
225             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
226             goto end;
227         case OPT_HELP:
228             opt_help(req_options);
229             ret = 0;
230             goto end;
231         case OPT_INFORM:
232             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
233                 goto opthelp;
234             break;
235         case OPT_OUTFORM:
236             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
237                 goto opthelp;
238             break;
239         case OPT_ENGINE:
240             (void)setup_engine(opt_arg(), 0);
241             break;
242         case OPT_KEYGEN_ENGINE:
243 #ifndef OPENSSL_NO_ENGINE
244             gen_eng = ENGINE_by_id(opt_arg());
245             if (gen_eng == NULL) {
246                 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
247                 goto opthelp;
248             }
249 #endif
250             break;
251         case OPT_KEY:
252             keyfile = opt_arg();
253             break;
254         case OPT_PUBKEY:
255             pubkey = 1;
256             break;
257         case OPT_NEW:
258             newreq = 1;
259             break;
260         case OPT_CONFIG:
261             template = opt_arg();
262             break;
263         case OPT_KEYFORM:
264             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &keyform))
265                 goto opthelp;
266             break;
267         case OPT_IN:
268             infile = opt_arg();
269             break;
270         case OPT_OUT:
271             outfile = opt_arg();
272             break;
273         case OPT_KEYOUT:
274             keyout = opt_arg();
275             break;
276         case OPT_PASSIN:
277             passargin = opt_arg();
278             break;
279         case OPT_PASSOUT:
280             passargout = opt_arg();
281             break;
282         case OPT_RAND:
283             inrand = opt_arg();
284             break;
285         case OPT_NEWKEY:
286             keyalg = opt_arg();
287             newreq = 1;
288             break;
289         case OPT_PKEYOPT:
290             if (!pkeyopts)
291                 pkeyopts = sk_OPENSSL_STRING_new_null();
292             if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
293                 goto opthelp;
294             break;
295         case OPT_SIGOPT:
296             if (!sigopts)
297                 sigopts = sk_OPENSSL_STRING_new_null();
298             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
299                 goto opthelp;
300             break;
301         case OPT_BATCH:
302             batch = 1;
303             break;
304         case OPT_NEWHDR:
305             newhdr = 1;
306             break;
307         case OPT_MODULUS:
308             modulus = 1;
309             break;
310         case OPT_VERIFY:
311             verify = 1;
312             break;
313         case OPT_NODES:
314             nodes = 1;
315             break;
316         case OPT_NOOUT:
317             noout = 1;
318             break;
319         case OPT_VERBOSE:
320             verbose = 1;
321             break;
322         case OPT_UTF8:
323             chtype = MBSTRING_UTF8;
324             break;
325         case OPT_NAMEOPT:
326             if (!set_name_ex(&nmflag, opt_arg()))
327                 goto opthelp;
328             break;
329         case OPT_REQOPT:
330             if (!set_cert_ex(&reqflag, opt_arg()))
331                 goto opthelp;
332             break;
333         case OPT_TEXT:
334             text = 1;
335             break;
336         case OPT_X509:
337             x509 = 1;
338             break;
339         case OPT_ASN1_KLUDGE:
340             kludge = 1;
341             break;
342         case OPT_NO_ASN1_KLUDGE:
343             kludge = 0;
344             break;
345             multirdn = 1;
346         case OPT_DAYS:
347             days = atoi(opt_arg());
348             break;
349         case OPT_SET_SERIAL:
350             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
351             if (serial == NULL)
352                 goto opthelp;
353             break;
354         case OPT_SUBJECT:
355             subject = 1;
356             break;
357         case OPT_SUBJ:
358             subj = opt_arg();
359             break;
360         case OPT_MULTIVALUE_RDN:
361             multirdn = 1;
362             break;
363         case OPT_EXTENSIONS:
364             extensions = opt_arg();
365             break;
366         case OPT_REQEXTS:
367             req_exts = opt_arg();
368             break;
369         case OPT_MD:
370             if (!opt_md(opt_unknown(), &md_alg))
371                 goto opthelp;
372             digest = md_alg;
373             break;
374         }
375     }
376     argc = opt_num_rest();
377     argv = opt_rest();
378     private = newreq && (pkey == NULL) ? 1 : 0;
379
380     if (!app_passwd(passargin, passargout, &passin, &passout)) {
381         BIO_printf(bio_err, "Error getting passwords\n");
382         goto end;
383     }
384
385     if (verbose)
386         BIO_printf(bio_err, "Using configuration from %s\n", template);
387     req_conf = app_load_config(template);
388     if (!app_load_modules(req_conf))
389         goto end;
390
391     if (req_conf != NULL) {
392         p = NCONF_get_string(req_conf, NULL, "oid_file");
393         if (p == NULL)
394             ERR_clear_error();
395         if (p != NULL) {
396             BIO *oid_bio;
397
398             oid_bio = BIO_new_file(p, "r");
399             if (oid_bio == NULL) {
400                 /*-
401                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
402                 ERR_print_errors(bio_err);
403                 */
404             } else {
405                 OBJ_create_objects(oid_bio);
406                 BIO_free(oid_bio);
407             }
408         }
409     }
410     if (!add_oid_section(req_conf))
411         goto end;
412
413     if (md_alg == NULL) {
414         p = NCONF_get_string(req_conf, SECTION, "default_md");
415         if (p == NULL)
416             ERR_clear_error();
417         else {
418             if (!opt_md(p, &md_alg))
419                 goto opthelp;
420             digest = md_alg;
421         }
422     }
423
424     if (!extensions) {
425         extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
426         if (!extensions)
427             ERR_clear_error();
428     }
429     if (extensions) {
430         /* Check syntax of file */
431         X509V3_CTX ctx;
432         X509V3_set_ctx_test(&ctx);
433         X509V3_set_nconf(&ctx, req_conf);
434         if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
435             BIO_printf(bio_err,
436                        "Error Loading extension section %s\n", extensions);
437             goto end;
438         }
439     }
440
441     if (!passin) {
442         passin = NCONF_get_string(req_conf, SECTION, "input_password");
443         if (!passin)
444             ERR_clear_error();
445     }
446
447     if (!passout) {
448         passout = NCONF_get_string(req_conf, SECTION, "output_password");
449         if (!passout)
450             ERR_clear_error();
451     }
452
453     p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
454     if (!p)
455         ERR_clear_error();
456
457     if (p && !ASN1_STRING_set_default_mask_asc(p)) {
458         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
459         goto end;
460     }
461
462     if (chtype != MBSTRING_UTF8) {
463         p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
464         if (!p)
465             ERR_clear_error();
466         else if (strcmp(p, "yes") == 0)
467             chtype = MBSTRING_UTF8;
468     }
469
470     if (!req_exts) {
471         req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
472         if (!req_exts)
473             ERR_clear_error();
474     }
475     if (req_exts) {
476         /* Check syntax of file */
477         X509V3_CTX ctx;
478         X509V3_set_ctx_test(&ctx);
479         X509V3_set_nconf(&ctx, req_conf);
480         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
481             BIO_printf(bio_err,
482                        "Error Loading request extension section %s\n",
483                        req_exts);
484             goto end;
485         }
486     }
487
488     if (keyfile != NULL) {
489         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
490         if (!pkey) {
491             /* load_key() has already printed an appropriate message */
492             goto end;
493         } else {
494             char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
495             if (randfile == NULL)
496                 ERR_clear_error();
497             app_RAND_load_file(randfile, 0);
498         }
499     }
500
501     if (newreq && (pkey == NULL)) {
502         char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
503         if (randfile == NULL)
504             ERR_clear_error();
505         app_RAND_load_file(randfile, 0);
506         if (inrand)
507             app_RAND_load_files(inrand);
508
509         if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
510             newkey = DEFAULT_KEY_LENGTH;
511         }
512
513         if (keyalg) {
514             genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
515                                     &keyalgstr, gen_eng);
516             if (!genctx)
517                 goto end;
518         }
519
520         if (newkey < MIN_KEY_LENGTH
521             && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
522             BIO_printf(bio_err, "private key length is too short,\n");
523             BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
524                        MIN_KEY_LENGTH, newkey);
525             goto end;
526         }
527
528         if (!genctx) {
529             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
530                                     &keyalgstr, gen_eng);
531             if (!genctx)
532                 goto end;
533         }
534
535         if (pkeyopts) {
536             char *genopt;
537             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
538                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
539                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
540                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
541                     ERR_print_errors(bio_err);
542                     goto end;
543                 }
544             }
545         }
546
547         BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
548                    newkey, keyalgstr);
549
550         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
551         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
552
553         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
554             BIO_puts(bio_err, "Error Generating Key\n");
555             goto end;
556         }
557
558         EVP_PKEY_CTX_free(genctx);
559         genctx = NULL;
560
561         app_RAND_write_file(randfile);
562
563         if (keyout == NULL) {
564             keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
565             if (keyout == NULL)
566                 ERR_clear_error();
567         }
568
569         if (keyout == NULL)
570             BIO_printf(bio_err, "writing new private key to stdout\n");
571         else
572             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
573         out = bio_open_owner(keyout, "w", private);
574         if (out == NULL)
575             goto end;
576
577         p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
578         if (p == NULL) {
579             ERR_clear_error();
580             p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
581             if (p == NULL)
582                 ERR_clear_error();
583         }
584         if ((p != NULL) && (strcmp(p, "no") == 0))
585             cipher = NULL;
586         if (nodes)
587             cipher = NULL;
588
589         i = 0;
590  loop:
591         assert(private);
592         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
593                                       NULL, 0, NULL, passout)) {
594             if ((ERR_GET_REASON(ERR_peek_error()) ==
595                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
596                 ERR_clear_error();
597                 i++;
598                 goto loop;
599             }
600             goto end;
601         }
602         BIO_free(out);
603         out = NULL;
604         BIO_printf(bio_err, "-----\n");
605     }
606
607     if (!newreq) {
608         /*
609          * Since we are using a pre-existing certificate request, the kludge
610          * 'format' info should not be changed.
611          */
612         kludge = -1;
613         in = bio_open_default(infile, RB(informat));
614         if (in == NULL)
615             goto end;
616
617         if (informat == FORMAT_ASN1)
618             req = d2i_X509_REQ_bio(in, NULL);
619         else
620             req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
621         if (req == NULL) {
622             BIO_printf(bio_err, "unable to load X509 request\n");
623             goto end;
624         }
625     }
626
627     if (newreq || x509) {
628         if (pkey == NULL) {
629             BIO_printf(bio_err, "you need to specify a private key\n");
630             goto end;
631         }
632
633         if (req == NULL) {
634             req = X509_REQ_new();
635             if (req == NULL) {
636                 goto end;
637             }
638
639             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
640             subj = NULL;        /* done processing '-subj' option */
641             if ((kludge > 0)
642                 && !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) {
643                 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
644                 req->req_info->attributes = NULL;
645             }
646             if (!i) {
647                 BIO_printf(bio_err, "problems making Certificate Request\n");
648                 goto end;
649             }
650         }
651         if (x509) {
652             EVP_PKEY *tmppkey;
653             X509V3_CTX ext_ctx;
654             if ((x509ss = X509_new()) == NULL)
655                 goto end;
656
657             /* Set version to V3 */
658             if (extensions && !X509_set_version(x509ss, 2))
659                 goto end;
660             if (serial) {
661                 if (!X509_set_serialNumber(x509ss, serial))
662                     goto end;
663             } else {
664                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
665                     goto end;
666             }
667
668             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
669                 goto end;
670             if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
671                 goto end;
672             if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
673                 goto end;
674             if (!X509_set_subject_name
675                 (x509ss, X509_REQ_get_subject_name(req)))
676                 goto end;
677             tmppkey = X509_REQ_get_pubkey(req);
678             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
679                 goto end;
680             EVP_PKEY_free(tmppkey);
681
682             /* Set up V3 context struct */
683
684             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
685             X509V3_set_nconf(&ext_ctx, req_conf);
686
687             /* Add extensions */
688             if (extensions && !X509V3_EXT_add_nconf(req_conf,
689                                                     &ext_ctx, extensions,
690                                                     x509ss)) {
691                 BIO_printf(bio_err, "Error Loading extension section %s\n",
692                            extensions);
693                 goto end;
694             }
695
696             i = do_X509_sign(x509ss, pkey, digest, sigopts);
697             if (!i) {
698                 ERR_print_errors(bio_err);
699                 goto end;
700             }
701         } else {
702             X509V3_CTX ext_ctx;
703
704             /* Set up V3 context struct */
705
706             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
707             X509V3_set_nconf(&ext_ctx, req_conf);
708
709             /* Add extensions */
710             if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
711                                                       &ext_ctx, req_exts,
712                                                       req)) {
713                 BIO_printf(bio_err, "Error Loading extension section %s\n",
714                            req_exts);
715                 goto end;
716             }
717             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
718             if (!i) {
719                 ERR_print_errors(bio_err);
720                 goto end;
721             }
722         }
723     }
724
725     if (subj && x509) {
726         BIO_printf(bio_err, "Cannot modify certificate subject\n");
727         goto end;
728     }
729
730     if (subj && !x509) {
731         if (verbose) {
732             BIO_printf(bio_err, "Modifying Request's Subject\n");
733             print_name(bio_err, "old subject=",
734                        X509_REQ_get_subject_name(req), nmflag);
735         }
736
737         if (build_subject(req, subj, chtype, multirdn) == 0) {
738             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
739             ret = 1;
740             goto end;
741         }
742
743         req->req_info->enc.modified = 1;
744
745         if (verbose) {
746             print_name(bio_err, "new subject=",
747                        X509_REQ_get_subject_name(req), nmflag);
748         }
749     }
750
751     if (verify && !x509) {
752         int tmp = 0;
753
754         if (pkey == NULL) {
755             pkey = X509_REQ_get_pubkey(req);
756             tmp = 1;
757             if (pkey == NULL)
758                 goto end;
759         }
760
761         i = X509_REQ_verify(req, pkey);
762         if (tmp) {
763             EVP_PKEY_free(pkey);
764             pkey = NULL;
765         }
766
767         if (i < 0) {
768             goto end;
769         } else if (i == 0) {
770             BIO_printf(bio_err, "verify failure\n");
771             ERR_print_errors(bio_err);
772         } else                  /* if (i > 0) */
773             BIO_printf(bio_err, "verify OK\n");
774     }
775
776     if (noout && !text && !modulus && !subject && !pubkey) {
777         ret = 0;
778         goto end;
779     }
780
781     out = bio_open_default(outfile,
782                            keyout != NULL && outfile != NULL &&
783                            strcmp(keyout, outfile) == 0 ? "a" : "w");
784     if (out == NULL)
785         goto end;
786
787     if (pubkey) {
788         EVP_PKEY *tpubkey;
789         tpubkey = X509_REQ_get_pubkey(req);
790         if (tpubkey == NULL) {
791             BIO_printf(bio_err, "Error getting public key\n");
792             ERR_print_errors(bio_err);
793             goto end;
794         }
795         PEM_write_bio_PUBKEY(out, tpubkey);
796         EVP_PKEY_free(tpubkey);
797     }
798
799     if (text) {
800         if (x509)
801             X509_print_ex(out, x509ss, nmflag, reqflag);
802         else
803             X509_REQ_print_ex(out, req, nmflag, reqflag);
804     }
805
806     if (subject) {
807         if (x509)
808             print_name(out, "subject=", X509_get_subject_name(x509ss),
809                        nmflag);
810         else
811             print_name(out, "subject=", X509_REQ_get_subject_name(req),
812                        nmflag);
813     }
814
815     if (modulus) {
816         EVP_PKEY *tpubkey;
817
818         if (x509)
819             tpubkey = X509_get_pubkey(x509ss);
820         else
821             tpubkey = X509_REQ_get_pubkey(req);
822         if (tpubkey == NULL) {
823             fprintf(stdout, "Modulus=unavailable\n");
824             goto end;
825         }
826         fprintf(stdout, "Modulus=");
827 #ifndef OPENSSL_NO_RSA
828         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
829             BN_print(out, tpubkey->pkey.rsa->n);
830         else
831 #endif
832             fprintf(stdout, "Wrong Algorithm type");
833         EVP_PKEY_free(tpubkey);
834         fprintf(stdout, "\n");
835     }
836
837     if (!noout && !x509) {
838         if (outformat == FORMAT_ASN1)
839             i = i2d_X509_REQ_bio(out, req);
840         else if (newhdr)
841             i = PEM_write_bio_X509_REQ_NEW(out, req);
842         else
843             i = PEM_write_bio_X509_REQ(out, req);
844         if (!i) {
845             BIO_printf(bio_err, "unable to write X509 request\n");
846             goto end;
847         }
848     }
849     if (!noout && x509 && (x509ss != NULL)) {
850         if (outformat == FORMAT_ASN1)
851             i = i2d_X509_bio(out, x509ss);
852         else
853             i = PEM_write_bio_X509(out, x509ss);
854         if (!i) {
855             BIO_printf(bio_err, "unable to write X509 certificate\n");
856             goto end;
857         }
858     }
859     ret = 0;
860  end:
861     if (ret) {
862         ERR_print_errors(bio_err);
863     }
864     NCONF_free(req_conf);
865     BIO_free(in);
866     BIO_free_all(out);
867     EVP_PKEY_free(pkey);
868     EVP_PKEY_CTX_free(genctx);
869     sk_OPENSSL_STRING_free(pkeyopts);
870     sk_OPENSSL_STRING_free(sigopts);
871 #ifndef OPENSSL_NO_ENGINE
872     ENGINE_free(gen_eng);
873 #endif
874     OPENSSL_free(keyalgstr);
875     X509_REQ_free(req);
876     X509_free(x509ss);
877     ASN1_INTEGER_free(serial);
878     OPENSSL_free(passin);
879     OPENSSL_free(passout);
880     OBJ_cleanup();
881     return (ret);
882 }
883
884 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
885                     int attribs, unsigned long chtype)
886 {
887     int ret = 0, i;
888     char no_prompt = 0;
889     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
890     char *tmp, *dn_sect, *attr_sect;
891
892     tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
893     if (tmp == NULL)
894         ERR_clear_error();
895     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
896         no_prompt = 1;
897
898     dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
899     if (dn_sect == NULL) {
900         BIO_printf(bio_err, "unable to find '%s' in config\n",
901                    DISTINGUISHED_NAME);
902         goto err;
903     }
904     dn_sk = NCONF_get_section(req_conf, dn_sect);
905     if (dn_sk == NULL) {
906         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
907         goto err;
908     }
909
910     attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
911     if (attr_sect == NULL) {
912         ERR_clear_error();
913         attr_sk = NULL;
914     } else {
915         attr_sk = NCONF_get_section(req_conf, attr_sect);
916         if (attr_sk == NULL) {
917             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
918             goto err;
919         }
920     }
921
922     /* setup version number */
923     if (!X509_REQ_set_version(req, 0L))
924         goto err;               /* version 1 */
925
926     if (subj)
927         i = build_subject(req, subj, chtype, multirdn);
928     else if (no_prompt)
929         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
930     else
931         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
932                         chtype);
933     if (!i)
934         goto err;
935
936     if (!X509_REQ_set_pubkey(req, pkey))
937         goto err;
938
939     ret = 1;
940  err:
941     return (ret);
942 }
943
944 /*
945  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
946  * where characters may be escaped by \
947  */
948 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
949                          int multirdn)
950 {
951     X509_NAME *n;
952
953     if ((n = parse_name(subject, chtype, multirdn)) == NULL)
954         return 0;
955
956     if (!X509_REQ_set_subject_name(req, n)) {
957         X509_NAME_free(n);
958         return 0;
959     }
960     X509_NAME_free(n);
961     return 1;
962 }
963
964 static int prompt_info(X509_REQ *req,
965                        STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
966                        STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
967                        int attribs, unsigned long chtype)
968 {
969     int i;
970     char *p, *q;
971     char buf[100];
972     int nid, mval;
973     long n_min, n_max;
974     char *type, *value;
975     const char *def;
976     CONF_VALUE *v;
977     X509_NAME *subj;
978     subj = X509_REQ_get_subject_name(req);
979
980     if (!batch) {
981         BIO_printf(bio_err,
982                    "You are about to be asked to enter information that will be incorporated\n");
983         BIO_printf(bio_err, "into your certificate request.\n");
984         BIO_printf(bio_err,
985                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
986         BIO_printf(bio_err,
987                    "There are quite a few fields but you can leave some blank\n");
988         BIO_printf(bio_err,
989                    "For some fields there will be a default value,\n");
990         BIO_printf(bio_err,
991                    "If you enter '.', the field will be left blank.\n");
992         BIO_printf(bio_err, "-----\n");
993     }
994
995     if (sk_CONF_VALUE_num(dn_sk)) {
996         i = -1;
997  start:for (;;) {
998             i++;
999             if (sk_CONF_VALUE_num(dn_sk) <= i)
1000                 break;
1001
1002             v = sk_CONF_VALUE_value(dn_sk, i);
1003             p = q = NULL;
1004             type = v->name;
1005             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1006                 !check_end(type, "_default") || !check_end(type, "_value"))
1007                 continue;
1008             /*
1009              * Skip past any leading X. X: X, etc to allow for multiple
1010              * instances
1011              */
1012             for (p = v->name; *p; p++)
1013                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1014                     p++;
1015                     if (*p)
1016                         type = p;
1017                     break;
1018                 }
1019             if (*type == '+') {
1020                 mval = -1;
1021                 type++;
1022             } else
1023                 mval = 0;
1024             /* If OBJ not recognised ignore it */
1025             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1026                 goto start;
1027             if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
1028                 >= (int)sizeof(buf)) {
1029                 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1030                 return 0;
1031             }
1032
1033             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1034                 ERR_clear_error();
1035                 def = "";
1036             }
1037
1038             BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
1039             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1040                 ERR_clear_error();
1041                 value = NULL;
1042             }
1043
1044             BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1045             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1046                 ERR_clear_error();
1047                 n_min = -1;
1048             }
1049
1050             BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1051             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1052                 ERR_clear_error();
1053                 n_max = -1;
1054             }
1055
1056             if (!add_DN_object(subj, v->value, def, value, nid,
1057                                n_min, n_max, chtype, mval))
1058                 return 0;
1059         }
1060         if (X509_NAME_entry_count(subj) == 0) {
1061             BIO_printf(bio_err,
1062                        "error, no objects specified in config file\n");
1063             return 0;
1064         }
1065
1066         if (attribs) {
1067             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1068                 && (!batch)) {
1069                 BIO_printf(bio_err,
1070                            "\nPlease enter the following 'extra' attributes\n");
1071                 BIO_printf(bio_err,
1072                            "to be sent with your certificate request\n");
1073             }
1074
1075             i = -1;
1076  start2:   for (;;) {
1077                 i++;
1078                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1079                     break;
1080
1081                 v = sk_CONF_VALUE_value(attr_sk, i);
1082                 type = v->name;
1083                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1084                     goto start2;
1085
1086                 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1087                     >= (int)sizeof(buf)) {
1088                     BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1089                     return 0;
1090                 }
1091
1092                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1093                     == NULL) {
1094                     ERR_clear_error();
1095                     def = "";
1096                 }
1097
1098                 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1099                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1100                     == NULL) {
1101                     ERR_clear_error();
1102                     value = NULL;
1103                 }
1104
1105                 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1106                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1107                     ERR_clear_error();
1108                     n_min = -1;
1109                 }
1110
1111                 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1112                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1113                     ERR_clear_error();
1114                     n_max = -1;
1115                 }
1116
1117                 if (!add_attribute_object(req,
1118                                           v->value, def, value, nid, n_min,
1119                                           n_max, chtype))
1120                     return 0;
1121             }
1122         }
1123     } else {
1124         BIO_printf(bio_err, "No template, please set one up.\n");
1125         return 0;
1126     }
1127
1128     return 1;
1129
1130 }
1131
1132 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1133                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1134                      unsigned long chtype)
1135 {
1136     int i;
1137     char *p, *q;
1138     char *type;
1139     CONF_VALUE *v;
1140     X509_NAME *subj;
1141
1142     subj = X509_REQ_get_subject_name(req);
1143
1144     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1145         int mval;
1146         v = sk_CONF_VALUE_value(dn_sk, i);
1147         p = q = NULL;
1148         type = v->name;
1149         /*
1150          * Skip past any leading X. X: X, etc to allow for multiple instances
1151          */
1152         for (p = v->name; *p; p++)
1153 #ifndef CHARSET_EBCDIC
1154             if ((*p == ':') || (*p == ',') || (*p == '.')) {
1155 #else
1156             if ((*p == os_toascii[':']) || (*p == os_toascii[','])
1157                 || (*p == os_toascii['.'])) {
1158 #endif
1159                 p++;
1160                 if (*p)
1161                     type = p;
1162                 break;
1163             }
1164 #ifndef CHARSET_EBCDIC
1165         if (*p == '+')
1166 #else
1167         if (*p == os_toascii['+'])
1168 #endif
1169         {
1170             p++;
1171             mval = -1;
1172         } else
1173             mval = 0;
1174         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1175                                         (unsigned char *)v->value, -1, -1,
1176                                         mval))
1177             return 0;
1178
1179     }
1180
1181     if (!X509_NAME_entry_count(subj)) {
1182         BIO_printf(bio_err, "error, no objects specified in config file\n");
1183         return 0;
1184     }
1185     if (attribs) {
1186         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1187             v = sk_CONF_VALUE_value(attr_sk, i);
1188             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1189                                            (unsigned char *)v->value, -1))
1190                 return 0;
1191         }
1192     }
1193     return 1;
1194 }
1195
1196 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1197                          char *value, int nid, int n_min, int n_max,
1198                          unsigned long chtype, int mval)
1199 {
1200     int i, ret = 0;
1201     char buf[1024];
1202  start:
1203     if (!batch)
1204         BIO_printf(bio_err, "%s [%s]:", text, def);
1205     (void)BIO_flush(bio_err);
1206     if (value != NULL) {
1207         BUF_strlcpy(buf, value, sizeof buf);
1208         BUF_strlcat(buf, "\n", sizeof buf);
1209         BIO_printf(bio_err, "%s\n", value);
1210     } else {
1211         buf[0] = '\0';
1212         if (!batch) {
1213             if (!fgets(buf, sizeof buf, stdin))
1214                 return 0;
1215         } else {
1216             buf[0] = '\n';
1217             buf[1] = '\0';
1218         }
1219     }
1220
1221     if (buf[0] == '\0')
1222         return (0);
1223     else if (buf[0] == '\n') {
1224         if ((def == NULL) || (def[0] == '\0'))
1225             return (1);
1226         BUF_strlcpy(buf, def, sizeof buf);
1227         BUF_strlcat(buf, "\n", sizeof buf);
1228     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1229         return (1);
1230
1231     i = strlen(buf);
1232     if (buf[i - 1] != '\n') {
1233         BIO_printf(bio_err, "weird input :-(\n");
1234         return (0);
1235     }
1236     buf[--i] = '\0';
1237 #ifdef CHARSET_EBCDIC
1238     ebcdic2ascii(buf, buf, i);
1239 #endif
1240     if (!req_check_len(i, n_min, n_max)) {
1241         if (batch || value)
1242             return 0;
1243         goto start;
1244     }
1245
1246     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1247                                     (unsigned char *)buf, -1, -1, mval))
1248         goto err;
1249     ret = 1;
1250  err:
1251     return (ret);
1252 }
1253
1254 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1255                                 char *value, int nid, int n_min,
1256                                 int n_max, unsigned long chtype)
1257 {
1258     int i;
1259     static char buf[1024];
1260
1261  start:
1262     if (!batch)
1263         BIO_printf(bio_err, "%s [%s]:", text, def);
1264     (void)BIO_flush(bio_err);
1265     if (value != NULL) {
1266         BUF_strlcpy(buf, value, sizeof buf);
1267         BUF_strlcat(buf, "\n", sizeof buf);
1268         BIO_printf(bio_err, "%s\n", value);
1269     } else {
1270         buf[0] = '\0';
1271         if (!batch) {
1272             if (!fgets(buf, sizeof buf, stdin))
1273                 return 0;
1274         } else {
1275             buf[0] = '\n';
1276             buf[1] = '\0';
1277         }
1278     }
1279
1280     if (buf[0] == '\0')
1281         return (0);
1282     else if (buf[0] == '\n') {
1283         if ((def == NULL) || (def[0] == '\0'))
1284             return (1);
1285         BUF_strlcpy(buf, def, sizeof buf);
1286         BUF_strlcat(buf, "\n", sizeof buf);
1287     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1288         return (1);
1289
1290     i = strlen(buf);
1291     if (buf[i - 1] != '\n') {
1292         BIO_printf(bio_err, "weird input :-(\n");
1293         return (0);
1294     }
1295     buf[--i] = '\0';
1296 #ifdef CHARSET_EBCDIC
1297     ebcdic2ascii(buf, buf, i);
1298 #endif
1299     if (!req_check_len(i, n_min, n_max)) {
1300         if (batch || value)
1301             return 0;
1302         goto start;
1303     }
1304
1305     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1306                                    (unsigned char *)buf, -1)) {
1307         BIO_printf(bio_err, "Error adding attribute\n");
1308         ERR_print_errors(bio_err);
1309         goto err;
1310     }
1311
1312     return (1);
1313  err:
1314     return (0);
1315 }
1316
1317 static int req_check_len(int len, int n_min, int n_max)
1318 {
1319     if ((n_min > 0) && (len < n_min)) {
1320         BIO_printf(bio_err,
1321                    "string is too short, it needs to be at least %d bytes long\n",
1322                    n_min);
1323         return (0);
1324     }
1325     if ((n_max >= 0) && (len > n_max)) {
1326         BIO_printf(bio_err,
1327                    "string is too long, it needs to be less than  %d bytes long\n",
1328                    n_max);
1329         return (0);
1330     }
1331     return (1);
1332 }
1333
1334 /* Check if the end of a string matches 'end' */
1335 static int check_end(const char *str, const char *end)
1336 {
1337     int elen, slen;
1338     const char *tmp;
1339     elen = strlen(end);
1340     slen = strlen(str);
1341     if (elen > slen)
1342         return 1;
1343     tmp = str + slen - elen;
1344     return strcmp(tmp, end);
1345 }
1346
1347 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1348                                     int *pkey_type, long *pkeylen,
1349                                     char **palgnam, ENGINE *keygen_engine)
1350 {
1351     EVP_PKEY_CTX *gctx = NULL;
1352     EVP_PKEY *param = NULL;
1353     long keylen = -1;
1354     BIO *pbio = NULL;
1355     const char *paramfile = NULL;
1356
1357     if (gstr == NULL) {
1358         *pkey_type = EVP_PKEY_RSA;
1359         keylen = *pkeylen;
1360     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1361         *pkey_type = EVP_PKEY_RSA;
1362         keylen = atol(gstr);
1363         *pkeylen = keylen;
1364     } else if (strncmp(gstr, "param:", 6) == 0)
1365         paramfile = gstr + 6;
1366     else {
1367         const char *p = strchr(gstr, ':');
1368         int len;
1369         ENGINE *tmpeng;
1370         const EVP_PKEY_ASN1_METHOD *ameth;
1371
1372         if (p)
1373             len = p - gstr;
1374         else
1375             len = strlen(gstr);
1376         /*
1377          * The lookup of a the string will cover all engines so keep a note
1378          * of the implementation.
1379          */
1380
1381         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1382
1383         if (!ameth) {
1384             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1385             return NULL;
1386         }
1387
1388         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1389 #ifndef OPENSSL_NO_ENGINE
1390         if (tmpeng)
1391             ENGINE_finish(tmpeng);
1392 #endif
1393         if (*pkey_type == EVP_PKEY_RSA) {
1394             if (p) {
1395                 keylen = atol(p + 1);
1396                 *pkeylen = keylen;
1397             } else
1398                 keylen = *pkeylen;
1399         } else if (p)
1400             paramfile = p + 1;
1401     }
1402
1403     if (paramfile) {
1404         pbio = BIO_new_file(paramfile, "r");
1405         if (!pbio) {
1406             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1407             return NULL;
1408         }
1409         param = PEM_read_bio_Parameters(pbio, NULL);
1410
1411         if (!param) {
1412             X509 *x;
1413             (void)BIO_reset(pbio);
1414             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1415             if (x) {
1416                 param = X509_get_pubkey(x);
1417                 X509_free(x);
1418             }
1419         }
1420
1421         BIO_free(pbio);
1422
1423         if (!param) {
1424             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1425             return NULL;
1426         }
1427         if (*pkey_type == -1)
1428             *pkey_type = EVP_PKEY_id(param);
1429         else if (*pkey_type != EVP_PKEY_base_id(param)) {
1430             BIO_printf(bio_err, "Key Type does not match parameters\n");
1431             EVP_PKEY_free(param);
1432             return NULL;
1433         }
1434     }
1435
1436     if (palgnam) {
1437         const EVP_PKEY_ASN1_METHOD *ameth;
1438         ENGINE *tmpeng;
1439         const char *anam;
1440         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1441         if (!ameth) {
1442             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1443             return NULL;
1444         }
1445         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1446         *palgnam = BUF_strdup(anam);
1447 #ifndef OPENSSL_NO_ENGINE
1448         if (tmpeng)
1449             ENGINE_finish(tmpeng);
1450 #endif
1451     }
1452
1453     if (param) {
1454         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1455         *pkeylen = EVP_PKEY_bits(param);
1456         EVP_PKEY_free(param);
1457     } else
1458         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1459
1460     if (!gctx) {
1461         BIO_puts(bio_err, "Error allocating keygen context\n");
1462         ERR_print_errors(bio_err);
1463         return NULL;
1464     }
1465
1466     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1467         BIO_puts(bio_err, "Error initializing keygen context\n");
1468         ERR_print_errors(bio_err);
1469         return NULL;
1470     }
1471 #ifndef OPENSSL_NO_RSA
1472     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1473         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1474             BIO_puts(bio_err, "Error setting RSA keysize\n");
1475             ERR_print_errors(bio_err);
1476             EVP_PKEY_CTX_free(gctx);
1477             return NULL;
1478         }
1479     }
1480 #endif
1481
1482     return gctx;
1483 }
1484
1485 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1486 {
1487     char c = '*';
1488     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1489     int p;
1490     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1491     if (p == 0)
1492         c = '.';
1493     if (p == 1)
1494         c = '+';
1495     if (p == 2)
1496         c = '*';
1497     if (p == 3)
1498         c = '\n';
1499     BIO_write(b, &c, 1);
1500     (void)BIO_flush(b);
1501     return 1;
1502 }
1503
1504 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1505                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1506 {
1507     EVP_PKEY_CTX *pkctx = NULL;
1508     int i;
1509
1510     EVP_MD_CTX_init(ctx);
1511     if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1512         return 0;
1513     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1514         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1515         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1516             BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1517             ERR_print_errors(bio_err);
1518             return 0;
1519         }
1520     }
1521     return 1;
1522 }
1523
1524 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1525                  STACK_OF(OPENSSL_STRING) *sigopts)
1526 {
1527     int rv;
1528     EVP_MD_CTX mctx;
1529
1530     EVP_MD_CTX_init(&mctx);
1531     rv = do_sign_init(&mctx, pkey, md, sigopts);
1532     if (rv > 0)
1533         rv = X509_sign_ctx(x, &mctx);
1534     EVP_MD_CTX_cleanup(&mctx);
1535     return rv > 0 ? 1 : 0;
1536 }
1537
1538 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1539                      STACK_OF(OPENSSL_STRING) *sigopts)
1540 {
1541     int rv;
1542     EVP_MD_CTX mctx;
1543
1544     EVP_MD_CTX_init(&mctx);
1545     rv = do_sign_init(&mctx, pkey, md, sigopts);
1546     if (rv > 0)
1547         rv = X509_REQ_sign_ctx(x, &mctx);
1548     EVP_MD_CTX_cleanup(&mctx);
1549     return rv > 0 ? 1 : 0;
1550 }
1551
1552 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1553                      STACK_OF(OPENSSL_STRING) *sigopts)
1554 {
1555     int rv;
1556     EVP_MD_CTX mctx;
1557
1558     EVP_MD_CTX_init(&mctx);
1559     rv = do_sign_init(&mctx, pkey, md, sigopts);
1560     if (rv > 0)
1561         rv = X509_CRL_sign_ctx(x, &mctx);
1562     EVP_MD_CTX_cleanup(&mctx);
1563     return rv > 0 ? 1 : 0;
1564 }