req.c revision 296341
167217Sn_hibma/* apps/req.c */
261560Sn_hibma/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
361560Sn_hibma * All rights reserved.
4113273Smdodd *
561560Sn_hibma * This package is an SSL implementation written
661560Sn_hibma * by Eric Young (eay@cryptsoft.com).
761560Sn_hibma * The implementation was written so as to conform with Netscapes SSL.
861560Sn_hibma *
961560Sn_hibma * This library is free for commercial and non-commercial use as long as
1061560Sn_hibma * the following conditions are aheared to.  The following conditions
1161560Sn_hibma * apply to all code found in this distribution, be it the RC4, RSA,
1261560Sn_hibma * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1361560Sn_hibma * included with this distribution is covered by the same copyright terms
1461560Sn_hibma * except that the holder is Tim Hudson (tjh@cryptsoft.com).
1561560Sn_hibma *
1661560Sn_hibma * Copyright remains Eric Young's, and as such any Copyright notices in
1761560Sn_hibma * the code are not to be removed.
1861560Sn_hibma * If this package is used in a product, Eric Young should be given attribution
1961560Sn_hibma * as the author of the parts of the library used.
2061560Sn_hibma * This can be in the form of a textual message at program startup or
2161560Sn_hibma * in documentation (online or textual) provided with the package.
2261560Sn_hibma *
2361560Sn_hibma * Redistribution and use in source and binary forms, with or without
2461560Sn_hibma * modification, are permitted provided that the following conditions
2561560Sn_hibma * are met:
2661560Sn_hibma * 1. Redistributions of source code must retain the copyright
2761560Sn_hibma *    notice, this list of conditions and the following disclaimer.
2861560Sn_hibma * 2. Redistributions in binary form must reproduce the above copyright
2984224Sdillon *    notice, this list of conditions and the following disclaimer in the
3084224Sdillon *    documentation and/or other materials provided with the distribution.
3184224Sdillon * 3. All advertising materials mentioning features or use of this software
3261560Sn_hibma *    must display the following acknowledgement:
3361560Sn_hibma *    "This product includes cryptographic software written by
3461560Sn_hibma *     Eric Young (eay@cryptsoft.com)"
3561560Sn_hibma *    The word 'cryptographic' can be left out if the rouines from the library
3661560Sn_hibma *    being used are not cryptographic related :-).
3761560Sn_hibma * 4. If you include any Windows specific code (or a derivative thereof) from
3861560Sn_hibma *    the apps directory (application code) you must include an acknowledgement:
3961560Sn_hibma *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40113273Smdodd *
4161560Sn_hibma * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4261560Sn_hibma * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43205728Skaiw * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44205728Skaiw * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45205728Skaiw * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46229387Smav * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4767217Sn_hibma * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48205728Skaiw * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49205728Skaiw * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50229387Smav * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5161560Sn_hibma * SUCH DAMAGE.
5261560Sn_hibma *
53205728Skaiw * The licence and distribution terms for any publically available version or
54205728Skaiw * derivative of this code cannot be changed.  i.e. this code cannot simply be
55205728Skaiw * copied and put under another distribution licence
56205728Skaiw * [including the GNU Public Licence.]
57205728Skaiw */
58205728Skaiw
59229387Smav/*
60205728Skaiw * Until the key-gen callbacks are modified to use newer prototypes, we allow
61205728Skaiw * deprecated functions for openssl-internal code
62205728Skaiw */
63205728Skaiw#ifdef OPENSSL_NO_DEPRECATED
64205728Skaiw# undef OPENSSL_NO_DEPRECATED
65205728Skaiw#endif
66205728Skaiw
67205728Skaiw#include <stdio.h>
68205728Skaiw#include <stdlib.h>
69205728Skaiw#include <time.h>
70205728Skaiw#include <string.h>
71205728Skaiw#ifdef OPENSSL_NO_STDIO
72205728Skaiw# define APPS_WIN16
73243058Smav#endif
74205728Skaiw#include "apps.h"
7561560Sn_hibma#include <openssl/bio.h>
76205728Skaiw#include <openssl/evp.h>
77205728Skaiw#include <openssl/conf.h>
78205728Skaiw#include <openssl/err.h>
7961560Sn_hibma#include <openssl/asn1.h>
8061560Sn_hibma#include <openssl/x509.h>
8161560Sn_hibma#include <openssl/x509v3.h>
82205728Skaiw#include <openssl/objects.h>
8361560Sn_hibma#include <openssl/pem.h>
8461560Sn_hibma#include <openssl/bn.h>
8561560Sn_hibma#ifndef OPENSSL_NO_RSA
8661560Sn_hibma# include <openssl/rsa.h>
8761560Sn_hibma#endif
8861560Sn_hibma#ifndef OPENSSL_NO_DSA
8961560Sn_hibma# include <openssl/dsa.h>
9061560Sn_hibma#endif
9161560Sn_hibma
9261560Sn_hibma#define SECTION         "req"
9361560Sn_hibma
9461560Sn_hibma#define BITS            "default_bits"
95205728Skaiw#define KEYFILE         "default_keyfile"
96205728Skaiw#define PROMPT          "prompt"
97205728Skaiw#define DISTINGUISHED_NAME      "distinguished_name"
98229387Smav#define ATTRIBUTES      "attributes"
99205728Skaiw#define V3_EXTENSIONS   "x509_extensions"
100205728Skaiw#define REQ_EXTENSIONS  "req_extensions"
101205728Skaiw#define STRING_MASK     "string_mask"
102205728Skaiw#define UTF8_IN         "utf8"
103205728Skaiw
104205728Skaiw#define DEFAULT_KEY_LENGTH      512
105205728Skaiw#define MIN_KEY_LENGTH          384
106205728Skaiw
107205728Skaiw#undef PROG
108205728Skaiw#define PROG    req_main
109205728Skaiw
110205728Skaiw/*-
111205728Skaiw * -inform arg  - input format - default PEM (DER or PEM)
112205728Skaiw * -outform arg - output format - default PEM
113205728Skaiw * -in arg      - input file - default stdin
114205728Skaiw * -out arg     - output file - default stdout
115205728Skaiw * -verify      - check request signature
116205728Skaiw * -noout       - don't print stuff out.
117205728Skaiw * -text        - print out human readable text.
118205728Skaiw * -nodes       - no des encryption
119229387Smav * -config file - Load configuration file.
120229387Smav * -key file    - make a request using key in file (or use it for verification).
121205728Skaiw * -keyform arg - key file format.
122205728Skaiw * -rand file(s) - load the file(s) into the PRNG.
123205728Skaiw * -newkey      - make a key and a request.
124205728Skaiw * -modulus     - print RSA modulus.
125205728Skaiw * -pubkey      - output Public Key.
126205728Skaiw * -x509        - output a self signed X509 structure instead.
127205728Skaiw * -asn1-kludge - output new certificate request in a format that some CA's
128205728Skaiw *                require.  This format is wrong
129205728Skaiw */
130205728Skaiw
131205728Skaiwstatic int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
132205728Skaiw                    int attribs, unsigned long chtype);
133205728Skaiwstatic int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
134205728Skaiw                         int multirdn);
135205728Skaiwstatic int prompt_info(X509_REQ *req,
136205728Skaiw                       STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
137205728Skaiw                       STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
138205728Skaiw                       int attribs, unsigned long chtype);
139205728Skaiwstatic int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
140205728Skaiw                     STACK_OF(CONF_VALUE) *attr, int attribs,
141229387Smav                     unsigned long chtype);
142229387Smavstatic int add_attribute_object(X509_REQ *req, char *text, const char *def,
143229387Smav                                char *value, int nid, int n_min, int n_max,
144229387Smav                                unsigned long chtype);
145229387Smavstatic int add_DN_object(X509_NAME *n, char *text, const char *def,
146229387Smav                         char *value, int nid, int n_min, int n_max,
147205728Skaiw                         unsigned long chtype, int mval);
148205728Skaiwstatic int genpkey_cb(EVP_PKEY_CTX *ctx);
149205728Skaiwstatic int req_check_len(int len, int n_min, int n_max);
150205728Skaiwstatic int check_end(const char *str, const char *end);
151205728Skaiwstatic EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr,
15261560Sn_hibma                                    int *pkey_type, long *pkeylen,
153243058Smav                                    char **palgnam, ENGINE *keygen_engine);
15461560Sn_hibma#ifndef MONOLITH
15561560Sn_hibmastatic char *default_config_file = NULL;
15661560Sn_hibma#endif
15761560Sn_hibmastatic CONF *req_conf = NULL;
15861560Sn_hibmastatic int batch = 0;
15961560Sn_hibma
16061560Sn_hibmaint MAIN(int, char **);
16161560Sn_hibma
162243058Smavint MAIN(int argc, char **argv)
16361560Sn_hibma{
16461560Sn_hibma    ENGINE *e = NULL, *gen_eng = NULL;
16561560Sn_hibma    unsigned long nmflag = 0, reqflag = 0;
166205728Skaiw    int ex = 1, x509 = 0, days = 30;
167205728Skaiw    X509 *x509ss = NULL;
168205728Skaiw    X509_REQ *req = NULL;
16961560Sn_hibma    EVP_PKEY_CTX *genctx = NULL;
17061560Sn_hibma    const char *keyalg = NULL;
17161560Sn_hibma    char *keyalgstr = NULL;
172205728Skaiw    STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
173205728Skaiw    EVP_PKEY *pkey = NULL;
174205728Skaiw    int i = 0, badops = 0, newreq = 0, verbose = 0, pkey_type = -1;
175205728Skaiw    long newkey = -1;
17661560Sn_hibma    BIO *in = NULL, *out = NULL;
17761560Sn_hibma    int informat, outformat, verify = 0, noout = 0, text = 0, keyform =
17861560Sn_hibma        FORMAT_PEM;
179205728Skaiw    int nodes = 0, kludge = 0, newhdr = 0, subject = 0, pubkey = 0;
180205728Skaiw    char *infile, *outfile, *prog, *keyfile = NULL, *template =
181205728Skaiw        NULL, *keyout = NULL;
182205728Skaiw#ifndef OPENSSL_NO_ENGINE
183205728Skaiw    char *engine = NULL;
18461560Sn_hibma#endif
185205728Skaiw    char *extensions = NULL;
186205728Skaiw    char *req_exts = NULL;
187113273Smdodd    const EVP_CIPHER *cipher = NULL;
188205728Skaiw    ASN1_INTEGER *serial = NULL;
189205728Skaiw    int modulus = 0;
190205728Skaiw    char *inrand = NULL;
191205728Skaiw    char *passargin = NULL, *passargout = NULL;
192205728Skaiw    char *passin = NULL, *passout = NULL;
193205728Skaiw    char *p;
194205728Skaiw    char *subj = NULL;
195205728Skaiw    int multirdn = 0;
196205728Skaiw    const EVP_MD *md_alg = NULL, *digest = NULL;
197205728Skaiw    unsigned long chtype = MBSTRING_ASC;
198205728Skaiw#ifndef MONOLITH
199205728Skaiw    char *to_free;
200205728Skaiw    long errline;
201205728Skaiw#endif
202205728Skaiw
203205728Skaiw    req_conf = NULL;
204205728Skaiw#ifndef OPENSSL_NO_DES
205205728Skaiw    cipher = EVP_des_ede3_cbc();
206205728Skaiw#endif
207113273Smdodd    apps_startup();
208113273Smdodd
209205728Skaiw    if (bio_err == NULL)
210205728Skaiw        if ((bio_err = BIO_new(BIO_s_file())) != NULL)
211205728Skaiw            BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
212243058Smav
213243058Smav    infile = NULL;
214113273Smdodd    outfile = NULL;
21561560Sn_hibma    informat = FORMAT_PEM;
216205728Skaiw    outformat = FORMAT_PEM;
217205728Skaiw
218205728Skaiw    prog = argv[0];
21961560Sn_hibma    argc--;
220205728Skaiw    argv++;
221205728Skaiw    while (argc >= 1) {
22261560Sn_hibma        if (strcmp(*argv, "-inform") == 0) {
223205728Skaiw            if (--argc < 1)
224205728Skaiw                goto bad;
22561560Sn_hibma            informat = str2fmt(*(++argv));
226205728Skaiw        } else if (strcmp(*argv, "-outform") == 0) {
227205728Skaiw            if (--argc < 1)
228205728Skaiw                goto bad;
229205728Skaiw            outformat = str2fmt(*(++argv));
230205728Skaiw        }
231205728Skaiw#ifndef OPENSSL_NO_ENGINE
232205728Skaiw        else if (strcmp(*argv, "-engine") == 0) {
233205728Skaiw            if (--argc < 1)
234205728Skaiw                goto bad;
235205728Skaiw            engine = *(++argv);
236205728Skaiw        } else if (strcmp(*argv, "-keygen_engine") == 0) {
237205728Skaiw            if (--argc < 1)
238205728Skaiw                goto bad;
239205728Skaiw            gen_eng = ENGINE_by_id(*(++argv));
240205728Skaiw            if (gen_eng == NULL) {
241205728Skaiw                BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
242113273Smdodd                goto end;
243205728Skaiw            }
244205728Skaiw        }
245205728Skaiw#endif
246205728Skaiw        else if (strcmp(*argv, "-key") == 0) {
247205728Skaiw            if (--argc < 1)
248205728Skaiw                goto bad;
24961560Sn_hibma            keyfile = *(++argv);
250229387Smav        } else if (strcmp(*argv, "-pubkey") == 0) {
251229387Smav            pubkey = 1;
25261560Sn_hibma        } else if (strcmp(*argv, "-new") == 0) {
25361560Sn_hibma            newreq = 1;
25461560Sn_hibma        } else if (strcmp(*argv, "-config") == 0) {
25561560Sn_hibma            if (--argc < 1)
256205728Skaiw                goto bad;
257205728Skaiw            template = *(++argv);
258205728Skaiw        } else if (strcmp(*argv, "-keyform") == 0) {
259205728Skaiw            if (--argc < 1)
260205728Skaiw                goto bad;
261205728Skaiw            keyform = str2fmt(*(++argv));
262205728Skaiw        } else if (strcmp(*argv, "-in") == 0) {
263205728Skaiw            if (--argc < 1)
264205728Skaiw                goto bad;
265205728Skaiw            infile = *(++argv);
266205728Skaiw        } else if (strcmp(*argv, "-out") == 0) {
267205728Skaiw            if (--argc < 1)
268205728Skaiw                goto bad;
26961560Sn_hibma            outfile = *(++argv);
27061560Sn_hibma        } else if (strcmp(*argv, "-keyout") == 0) {
271205728Skaiw            if (--argc < 1)
272205728Skaiw                goto bad;
273205728Skaiw            keyout = *(++argv);
274205728Skaiw        } else if (strcmp(*argv, "-passin") == 0) {
27561560Sn_hibma            if (--argc < 1)
27661560Sn_hibma                goto bad;
27761560Sn_hibma            passargin = *(++argv);
27861560Sn_hibma        } else if (strcmp(*argv, "-passout") == 0) {
27961560Sn_hibma            if (--argc < 1)
280205728Skaiw                goto bad;
281205728Skaiw            passargout = *(++argv);
28261560Sn_hibma        } else if (strcmp(*argv, "-rand") == 0) {
283205728Skaiw            if (--argc < 1)
28461560Sn_hibma                goto bad;
28561560Sn_hibma            inrand = *(++argv);
28661560Sn_hibma        } else if (strcmp(*argv, "-newkey") == 0) {
287205728Skaiw            if (--argc < 1)
28861560Sn_hibma                goto bad;
28961560Sn_hibma            keyalg = *(++argv);
290205728Skaiw            newreq = 1;
291205728Skaiw        } else if (strcmp(*argv, "-pkeyopt") == 0) {
29261560Sn_hibma            if (--argc < 1)
29361560Sn_hibma                goto bad;
294205728Skaiw            if (!pkeyopts)
295205728Skaiw                pkeyopts = sk_OPENSSL_STRING_new_null();
296205728Skaiw            if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, *(++argv)))
297205728Skaiw                goto bad;
29861560Sn_hibma        } else if (strcmp(*argv, "-sigopt") == 0) {
29961560Sn_hibma            if (--argc < 1)
300205728Skaiw                goto bad;
301205728Skaiw            if (!sigopts)
302205728Skaiw                sigopts = sk_OPENSSL_STRING_new_null();
303205728Skaiw            if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
304205728Skaiw                goto bad;
30561560Sn_hibma        } else if (strcmp(*argv, "-batch") == 0)
30661560Sn_hibma            batch = 1;
307205728Skaiw        else if (strcmp(*argv, "-newhdr") == 0)
308205728Skaiw            newhdr = 1;
30961560Sn_hibma        else if (strcmp(*argv, "-modulus") == 0)
31061560Sn_hibma            modulus = 1;
31161560Sn_hibma        else if (strcmp(*argv, "-verify") == 0)
312205728Skaiw            verify = 1;
31361560Sn_hibma        else if (strcmp(*argv, "-nodes") == 0)
314205728Skaiw            nodes = 1;
315205728Skaiw        else if (strcmp(*argv, "-noout") == 0)
31661560Sn_hibma            noout = 1;
317205728Skaiw        else if (strcmp(*argv, "-verbose") == 0)
318205728Skaiw            verbose = 1;
319205728Skaiw        else if (strcmp(*argv, "-utf8") == 0)
320205728Skaiw            chtype = MBSTRING_UTF8;
32161560Sn_hibma        else if (strcmp(*argv, "-nameopt") == 0) {
322205728Skaiw            if (--argc < 1)
323205728Skaiw                goto bad;
324205728Skaiw            if (!set_name_ex(&nmflag, *(++argv)))
325205728Skaiw                goto bad;
326205728Skaiw        } else if (strcmp(*argv, "-reqopt") == 0) {
327205728Skaiw            if (--argc < 1)
328205728Skaiw                goto bad;
329205728Skaiw            if (!set_cert_ex(&reqflag, *(++argv)))
330205728Skaiw                goto bad;
331205728Skaiw        } else if (strcmp(*argv, "-subject") == 0)
33261560Sn_hibma            subject = 1;
333224511Smav        else if (strcmp(*argv, "-text") == 0)
334224511Smav            text = 1;
33561560Sn_hibma        else if (strcmp(*argv, "-x509") == 0)
336205728Skaiw            x509 = 1;
33761560Sn_hibma        else if (strcmp(*argv, "-asn1-kludge") == 0)
338205728Skaiw            kludge = 1;
339205728Skaiw        else if (strcmp(*argv, "-no-asn1-kludge") == 0)
340205728Skaiw            kludge = 0;
341205728Skaiw        else if (strcmp(*argv, "-subj") == 0) {
342205728Skaiw            if (--argc < 1)
34361560Sn_hibma                goto bad;
34461560Sn_hibma            subj = *(++argv);
34561560Sn_hibma        } else if (strcmp(*argv, "-multivalue-rdn") == 0)
34661560Sn_hibma            multirdn = 1;
34761560Sn_hibma        else if (strcmp(*argv, "-days") == 0) {
348205728Skaiw            if (--argc < 1)
349205728Skaiw                goto bad;
350205728Skaiw            days = atoi(*(++argv));
35161560Sn_hibma            if (days == 0)
352205728Skaiw                days = 30;
353205728Skaiw        } else if (strcmp(*argv, "-set_serial") == 0) {
35461560Sn_hibma            if (--argc < 1)
35561560Sn_hibma                goto bad;
35661560Sn_hibma            serial = s2i_ASN1_INTEGER(NULL, *(++argv));
357205728Skaiw            if (!serial)
358205728Skaiw                goto bad;
359205728Skaiw        } else if (strcmp(*argv, "-extensions") == 0) {
360205728Skaiw            if (--argc < 1)
36161560Sn_hibma                goto bad;
36261560Sn_hibma            extensions = *(++argv);
36361560Sn_hibma        } else if (strcmp(*argv, "-reqexts") == 0) {
36461560Sn_hibma            if (--argc < 1)
365205728Skaiw                goto bad;
36661560Sn_hibma            req_exts = *(++argv);
367113273Smdodd        } else if ((md_alg = EVP_get_digestbyname(&((*argv)[1]))) != NULL) {
36861560Sn_hibma            /* ok */
36961560Sn_hibma            digest = md_alg;
37061560Sn_hibma        } else {
37161560Sn_hibma            BIO_printf(bio_err, "unknown option %s\n", *argv);
37261560Sn_hibma            badops = 1;
37361560Sn_hibma            break;
37461560Sn_hibma        }
37561560Sn_hibma        argc--;
37661560Sn_hibma        argv++;
37761560Sn_hibma    }
37861560Sn_hibma
37961560Sn_hibma    if (badops) {
38061560Sn_hibma bad:
381205728Skaiw        BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
38261560Sn_hibma        BIO_printf(bio_err, "where options  are\n");
38361560Sn_hibma        BIO_printf(bio_err, " -inform arg    input format - DER or PEM\n");
38461560Sn_hibma        BIO_printf(bio_err, " -outform arg   output format - DER or PEM\n");
38561560Sn_hibma        BIO_printf(bio_err, " -in arg        input file\n");
38661560Sn_hibma        BIO_printf(bio_err, " -out arg       output file\n");
38761560Sn_hibma        BIO_printf(bio_err, " -text          text form of request\n");
38861560Sn_hibma        BIO_printf(bio_err, " -pubkey        output public key\n");
38961560Sn_hibma        BIO_printf(bio_err, " -noout         do not output REQ\n");
39061560Sn_hibma        BIO_printf(bio_err, " -verify        verify signature on REQ\n");
39161560Sn_hibma        BIO_printf(bio_err, " -modulus       RSA modulus\n");
39261560Sn_hibma        BIO_printf(bio_err, " -nodes         don't encrypt the output key\n");
393205728Skaiw#ifndef OPENSSL_NO_ENGINE
394205728Skaiw        BIO_printf(bio_err,
39561560Sn_hibma                   " -engine e      use engine e, possibly a hardware device\n");
39661560Sn_hibma#endif
397235866Smav        BIO_printf(bio_err, " -subject       output the request's subject\n");
39861560Sn_hibma        BIO_printf(bio_err, " -passin        private key password source\n");
39961560Sn_hibma        BIO_printf(bio_err,
400205728Skaiw                   " -key file      use the private key contained in file\n");
401205728Skaiw        BIO_printf(bio_err, " -keyform arg   key file format\n");
40261560Sn_hibma        BIO_printf(bio_err, " -keyout arg    file to send the key to\n");
403205728Skaiw        BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
404205728Skaiw                   LIST_SEPARATOR_CHAR);
405205728Skaiw        BIO_printf(bio_err,
406205728Skaiw                   "                load the file (or the files in the directory) into\n");
407205728Skaiw        BIO_printf(bio_err, "                the random number generator\n");
408205728Skaiw        BIO_printf(bio_err,
409205728Skaiw                   " -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
410205728Skaiw        BIO_printf(bio_err,
411205728Skaiw                   " -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
412205728Skaiw#ifndef OPENSSL_NO_ECDSA
41361560Sn_hibma        BIO_printf(bio_err,
414205728Skaiw                   " -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n");
415205728Skaiw#endif
416205728Skaiw        BIO_printf(bio_err,
417205728Skaiw                   " -[digest]      Digest to sign with (md5, sha1, md2, mdc2, md4)\n");
418205728Skaiw        BIO_printf(bio_err, " -config file   request template file.\n");
419205728Skaiw        BIO_printf(bio_err,
420205728Skaiw                   " -subj arg      set or modify request subject\n");
421205728Skaiw        BIO_printf(bio_err,
422205728Skaiw                   " -multivalue-rdn enable support for multivalued RDNs\n");
423205728Skaiw        BIO_printf(bio_err, " -new           new request.\n");
42461560Sn_hibma        BIO_printf(bio_err,
42561560Sn_hibma                   " -batch         do not ask anything during request generation\n");
426205728Skaiw        BIO_printf(bio_err,
42761560Sn_hibma                   " -x509          output a x509 structure instead of a cert. req.\n");
42861560Sn_hibma        BIO_printf(bio_err,
42961560Sn_hibma                   " -days          number of days a certificate generated by -x509 is valid for.\n");
43061560Sn_hibma        BIO_printf(bio_err,
43161560Sn_hibma                   " -set_serial    serial number to use for a certificate generated by -x509.\n");
432205728Skaiw        BIO_printf(bio_err,
433205728Skaiw                   " -newhdr        output \"NEW\" in the header lines\n");
434205728Skaiw        BIO_printf(bio_err,
435205728Skaiw                   " -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
436205728Skaiw        BIO_printf(bio_err,
437205728Skaiw                   "                have been reported as requiring\n");
438205728Skaiw        BIO_printf(bio_err,
439205728Skaiw                   " -extensions .. specify certificate extension section (override value in config file)\n");
440205728Skaiw        BIO_printf(bio_err,
441205728Skaiw                   " -reqexts ..    specify request extension section (override value in config file)\n");
442205728Skaiw        BIO_printf(bio_err,
44361560Sn_hibma                   " -utf8          input characters are UTF8 (default ASCII)\n");
444205728Skaiw        BIO_printf(bio_err,
445205728Skaiw                   " -nameopt arg    - various certificate name options\n");
446205728Skaiw        BIO_printf(bio_err,
44761560Sn_hibma                   " -reqopt arg    - various request text options\n\n");
44861560Sn_hibma        goto end;
449205728Skaiw    }
450205728Skaiw
451205728Skaiw    ERR_load_crypto_strings();
452205728Skaiw    if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
453205728Skaiw        BIO_printf(bio_err, "Error getting passwords\n");
454205728Skaiw        goto end;
455205728Skaiw    }
45661560Sn_hibma#ifndef MONOLITH                /* else this has happened in openssl.c
457205728Skaiw                                 * (global `config') */
458205728Skaiw    /* Lets load up our environment a little */
459205728Skaiw    p = getenv("OPENSSL_CONF");
460205728Skaiw    if (p == NULL)
461205728Skaiw        p = getenv("SSLEAY_CONF");
462205728Skaiw    if (p == NULL)
463205728Skaiw        p = to_free = make_config_name();
464205728Skaiw    default_config_file = p;
465205728Skaiw    config = NCONF_new(NULL);
466205728Skaiw    i = NCONF_load(config, p, &errline);
467205728Skaiw#endif
468205728Skaiw
469205728Skaiw    if (template != NULL) {
470205728Skaiw        long errline = -1;
471205728Skaiw
472205728Skaiw        if (verbose)
473205728Skaiw            BIO_printf(bio_err, "Using configuration from %s\n", template);
474205728Skaiw        req_conf = NCONF_new(NULL);
475205728Skaiw        i = NCONF_load(req_conf, template, &errline);
476205728Skaiw        if (i == 0) {
477205728Skaiw            BIO_printf(bio_err, "error on line %ld of %s\n", errline,
478205728Skaiw                       template);
479205728Skaiw            goto end;
48061560Sn_hibma        }
48161560Sn_hibma    } else {
48261560Sn_hibma        req_conf = config;
48361560Sn_hibma
48461560Sn_hibma        if (req_conf == NULL) {
48561560Sn_hibma            BIO_printf(bio_err, "Unable to load config info from %s\n",
48661560Sn_hibma                       default_config_file);
48761560Sn_hibma            if (newreq)
48861560Sn_hibma                goto end;
48961560Sn_hibma        } else if (verbose)
49061560Sn_hibma            BIO_printf(bio_err, "Using configuration from %s\n",
49161560Sn_hibma                       default_config_file);
49261560Sn_hibma    }
49361560Sn_hibma
49461560Sn_hibma    if (req_conf != NULL) {
49561560Sn_hibma        if (!load_config(bio_err, req_conf))
49661560Sn_hibma            goto end;
49761560Sn_hibma        p = NCONF_get_string(req_conf, NULL, "oid_file");
49861560Sn_hibma        if (p == NULL)
49961560Sn_hibma            ERR_clear_error();
50061560Sn_hibma        if (p != NULL) {
50161560Sn_hibma            BIO *oid_bio;
50261560Sn_hibma
503205728Skaiw            oid_bio = BIO_new_file(p, "r");
50461560Sn_hibma            if (oid_bio == NULL) {
50561560Sn_hibma                /*-
50661560Sn_hibma                BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
507205728Skaiw                ERR_print_errors(bio_err);
50861560Sn_hibma                */
50961560Sn_hibma            } else {
510205728Skaiw                OBJ_create_objects(oid_bio);
51161560Sn_hibma                BIO_free(oid_bio);
51261560Sn_hibma            }
51361560Sn_hibma        }
514243058Smav    }
515243058Smav    if (!add_oid_section(bio_err, req_conf))
516243058Smav        goto end;
517243058Smav
518243058Smav    if (md_alg == NULL) {
519243058Smav        p = NCONF_get_string(req_conf, SECTION, "default_md");
520243058Smav        if (p == NULL)
521243058Smav            ERR_clear_error();
522243058Smav        if (p != NULL) {
523243058Smav            if ((md_alg = EVP_get_digestbyname(p)) != NULL)
524243058Smav                digest = md_alg;
525243058Smav        }
526243058Smav    }
527113273Smdodd
52861560Sn_hibma    if (!extensions) {
52961560Sn_hibma        extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
530205728Skaiw        if (!extensions)
531205728Skaiw            ERR_clear_error();
532205728Skaiw    }
533205728Skaiw    if (extensions) {
534224511Smav        /* Check syntax of file */
53561560Sn_hibma        X509V3_CTX ctx;
536205728Skaiw        X509V3_set_ctx_test(&ctx);
537205728Skaiw        X509V3_set_nconf(&ctx, req_conf);
538205728Skaiw        if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
53961560Sn_hibma            BIO_printf(bio_err,
540205728Skaiw                       "Error Loading extension section %s\n", extensions);
541243058Smav            goto end;
542205728Skaiw        }
543205728Skaiw    }
544205728Skaiw
545205728Skaiw    if (!passin) {
546205728Skaiw        passin = NCONF_get_string(req_conf, SECTION, "input_password");
547205728Skaiw        if (!passin)
548205728Skaiw            ERR_clear_error();
549205728Skaiw    }
550224511Smav
551224511Smav    if (!passout) {
55261560Sn_hibma        passout = NCONF_get_string(req_conf, SECTION, "output_password");
55361560Sn_hibma        if (!passout)
55461560Sn_hibma            ERR_clear_error();
555205728Skaiw    }
556205728Skaiw
557205728Skaiw    p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
558205728Skaiw    if (!p)
559205728Skaiw        ERR_clear_error();
560205728Skaiw
561205728Skaiw    if (p && !ASN1_STRING_set_default_mask_asc(p)) {
562205728Skaiw        BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
563224511Smav        goto end;
56461560Sn_hibma    }
56561560Sn_hibma
56661560Sn_hibma    if (chtype != MBSTRING_UTF8) {
567113273Smdodd        p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
568113273Smdodd        if (!p)
56961560Sn_hibma            ERR_clear_error();
570205728Skaiw        else if (!strcmp(p, "yes"))
57161560Sn_hibma            chtype = MBSTRING_UTF8;
572205728Skaiw    }
57361560Sn_hibma
57461560Sn_hibma    if (!req_exts) {
57561560Sn_hibma        req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
57661560Sn_hibma        if (!req_exts)
57761560Sn_hibma            ERR_clear_error();
57861560Sn_hibma    }
57961560Sn_hibma    if (req_exts) {
58061560Sn_hibma        /* Check syntax of file */
58161560Sn_hibma        X509V3_CTX ctx;
582        X509V3_set_ctx_test(&ctx);
583        X509V3_set_nconf(&ctx, req_conf);
584        if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
585            BIO_printf(bio_err,
586                       "Error Loading request extension section %s\n",
587                       req_exts);
588            goto end;
589        }
590    }
591
592    in = BIO_new(BIO_s_file());
593    out = BIO_new(BIO_s_file());
594    if ((in == NULL) || (out == NULL))
595        goto end;
596
597#ifndef OPENSSL_NO_ENGINE
598    e = setup_engine(bio_err, engine, 0);
599#endif
600
601    if (keyfile != NULL) {
602        pkey = load_key(bio_err, keyfile, keyform, 0, passin, e,
603                        "Private Key");
604        if (!pkey) {
605            /*
606             * load_key() has already printed an appropriate message
607             */
608            goto end;
609        } else {
610            char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
611            if (randfile == NULL)
612                ERR_clear_error();
613            app_RAND_load_file(randfile, bio_err, 0);
614        }
615    }
616
617    if (newreq && (pkey == NULL)) {
618        char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
619        if (randfile == NULL)
620            ERR_clear_error();
621        app_RAND_load_file(randfile, bio_err, 0);
622        if (inrand)
623            app_RAND_load_files(inrand);
624
625        if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
626            newkey = DEFAULT_KEY_LENGTH;
627        }
628
629        if (keyalg) {
630            genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey,
631                                    &keyalgstr, gen_eng);
632            if (!genctx)
633                goto end;
634        }
635
636        if (newkey < MIN_KEY_LENGTH
637            && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
638            BIO_printf(bio_err, "private key length is too short,\n");
639            BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
640                       MIN_KEY_LENGTH, newkey);
641            goto end;
642        }
643
644        if (!genctx) {
645            genctx = set_keygen_ctx(bio_err, NULL, &pkey_type, &newkey,
646                                    &keyalgstr, gen_eng);
647            if (!genctx)
648                goto end;
649        }
650
651        if (pkeyopts) {
652            char *genopt;
653            for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
654                genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
655                if (pkey_ctrl_string(genctx, genopt) <= 0) {
656                    BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
657                    ERR_print_errors(bio_err);
658                    goto end;
659                }
660            }
661        }
662
663        BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
664                   newkey, keyalgstr);
665
666        EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
667        EVP_PKEY_CTX_set_app_data(genctx, bio_err);
668
669        if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
670            BIO_puts(bio_err, "Error Generating Key\n");
671            goto end;
672        }
673
674        EVP_PKEY_CTX_free(genctx);
675        genctx = NULL;
676
677        app_RAND_write_file(randfile, bio_err);
678
679        if (keyout == NULL) {
680            keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
681            if (keyout == NULL)
682                ERR_clear_error();
683        }
684
685        if (keyout == NULL) {
686            BIO_printf(bio_err, "writing new private key to stdout\n");
687            BIO_set_fp(out, stdout, BIO_NOCLOSE);
688#ifdef OPENSSL_SYS_VMS
689            {
690                BIO *tmpbio = BIO_new(BIO_f_linebuffer());
691                out = BIO_push(tmpbio, out);
692            }
693#endif
694        } else {
695            BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
696            if (BIO_write_filename(out, keyout) <= 0) {
697                perror(keyout);
698                goto end;
699            }
700        }
701
702        p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
703        if (p == NULL) {
704            ERR_clear_error();
705            p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
706            if (p == NULL)
707                ERR_clear_error();
708        }
709        if ((p != NULL) && (strcmp(p, "no") == 0))
710            cipher = NULL;
711        if (nodes)
712            cipher = NULL;
713
714        i = 0;
715 loop:
716        if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
717                                      NULL, 0, NULL, passout)) {
718            if ((ERR_GET_REASON(ERR_peek_error()) ==
719                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
720                ERR_clear_error();
721                i++;
722                goto loop;
723            }
724            goto end;
725        }
726        BIO_printf(bio_err, "-----\n");
727    }
728
729    if (!newreq) {
730        /*
731         * Since we are using a pre-existing certificate request, the kludge
732         * 'format' info should not be changed.
733         */
734        kludge = -1;
735        if (infile == NULL)
736            BIO_set_fp(in, stdin, BIO_NOCLOSE);
737        else {
738            if (BIO_read_filename(in, infile) <= 0) {
739                perror(infile);
740                goto end;
741            }
742        }
743
744        if (informat == FORMAT_ASN1)
745            req = d2i_X509_REQ_bio(in, NULL);
746        else if (informat == FORMAT_PEM)
747            req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
748        else {
749            BIO_printf(bio_err,
750                       "bad input format specified for X509 request\n");
751            goto end;
752        }
753        if (req == NULL) {
754            BIO_printf(bio_err, "unable to load X509 request\n");
755            goto end;
756        }
757    }
758
759    if (newreq || x509) {
760        if (pkey == NULL) {
761            BIO_printf(bio_err, "you need to specify a private key\n");
762            goto end;
763        }
764
765        if (req == NULL) {
766            req = X509_REQ_new();
767            if (req == NULL) {
768                goto end;
769            }
770
771            i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
772            subj = NULL;        /* done processing '-subj' option */
773            if ((kludge > 0)
774                && !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) {
775                sk_X509_ATTRIBUTE_free(req->req_info->attributes);
776                req->req_info->attributes = NULL;
777            }
778            if (!i) {
779                BIO_printf(bio_err, "problems making Certificate Request\n");
780                goto end;
781            }
782        }
783        if (x509) {
784            EVP_PKEY *tmppkey;
785            X509V3_CTX ext_ctx;
786            if ((x509ss = X509_new()) == NULL)
787                goto end;
788
789            /* Set version to V3 */
790            if (extensions && !X509_set_version(x509ss, 2))
791                goto end;
792            if (serial) {
793                if (!X509_set_serialNumber(x509ss, serial))
794                    goto end;
795            } else {
796                if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
797                    goto end;
798            }
799
800            if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
801                goto end;
802            if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
803                goto end;
804            if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
805                goto end;
806            if (!X509_set_subject_name
807                (x509ss, X509_REQ_get_subject_name(req)))
808                goto end;
809            tmppkey = X509_REQ_get_pubkey(req);
810            if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
811                goto end;
812            EVP_PKEY_free(tmppkey);
813
814            /* Set up V3 context struct */
815
816            X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
817            X509V3_set_nconf(&ext_ctx, req_conf);
818
819            /* Add extensions */
820            if (extensions && !X509V3_EXT_add_nconf(req_conf,
821                                                    &ext_ctx, extensions,
822                                                    x509ss)) {
823                BIO_printf(bio_err, "Error Loading extension section %s\n",
824                           extensions);
825                goto end;
826            }
827
828            i = do_X509_sign(bio_err, x509ss, pkey, digest, sigopts);
829            if (!i) {
830                ERR_print_errors(bio_err);
831                goto end;
832            }
833        } else {
834            X509V3_CTX ext_ctx;
835
836            /* Set up V3 context struct */
837
838            X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
839            X509V3_set_nconf(&ext_ctx, req_conf);
840
841            /* Add extensions */
842            if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
843                                                      &ext_ctx, req_exts,
844                                                      req)) {
845                BIO_printf(bio_err, "Error Loading extension section %s\n",
846                           req_exts);
847                goto end;
848            }
849            i = do_X509_REQ_sign(bio_err, req, pkey, digest, sigopts);
850            if (!i) {
851                ERR_print_errors(bio_err);
852                goto end;
853            }
854        }
855    }
856
857    if (subj && x509) {
858        BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
859        goto end;
860    }
861
862    if (subj && !x509) {
863        if (verbose) {
864            BIO_printf(bio_err, "Modifying Request's Subject\n");
865            print_name(bio_err, "old subject=",
866                       X509_REQ_get_subject_name(req), nmflag);
867        }
868
869        if (build_subject(req, subj, chtype, multirdn) == 0) {
870            BIO_printf(bio_err, "ERROR: cannot modify subject\n");
871            ex = 1;
872            goto end;
873        }
874
875        req->req_info->enc.modified = 1;
876
877        if (verbose) {
878            print_name(bio_err, "new subject=",
879                       X509_REQ_get_subject_name(req), nmflag);
880        }
881    }
882
883    if (verify && !x509) {
884        int tmp = 0;
885
886        if (pkey == NULL) {
887            pkey = X509_REQ_get_pubkey(req);
888            tmp = 1;
889            if (pkey == NULL)
890                goto end;
891        }
892
893        i = X509_REQ_verify(req, pkey);
894        if (tmp) {
895            EVP_PKEY_free(pkey);
896            pkey = NULL;
897        }
898
899        if (i < 0) {
900            goto end;
901        } else if (i == 0) {
902            BIO_printf(bio_err, "verify failure\n");
903            ERR_print_errors(bio_err);
904        } else                  /* if (i > 0) */
905            BIO_printf(bio_err, "verify OK\n");
906    }
907
908    if (noout && !text && !modulus && !subject && !pubkey) {
909        ex = 0;
910        goto end;
911    }
912
913    if (outfile == NULL) {
914        BIO_set_fp(out, stdout, BIO_NOCLOSE);
915#ifdef OPENSSL_SYS_VMS
916        {
917            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
918            out = BIO_push(tmpbio, out);
919        }
920#endif
921    } else {
922        if ((keyout != NULL) && (strcmp(outfile, keyout) == 0))
923            i = (int)BIO_append_filename(out, outfile);
924        else
925            i = (int)BIO_write_filename(out, outfile);
926        if (!i) {
927            perror(outfile);
928            goto end;
929        }
930    }
931
932    if (pubkey) {
933        EVP_PKEY *tpubkey;
934        tpubkey = X509_REQ_get_pubkey(req);
935        if (tpubkey == NULL) {
936            BIO_printf(bio_err, "Error getting public key\n");
937            ERR_print_errors(bio_err);
938            goto end;
939        }
940        PEM_write_bio_PUBKEY(out, tpubkey);
941        EVP_PKEY_free(tpubkey);
942    }
943
944    if (text) {
945        if (x509)
946            X509_print_ex(out, x509ss, nmflag, reqflag);
947        else
948            X509_REQ_print_ex(out, req, nmflag, reqflag);
949    }
950
951    if (subject) {
952        if (x509)
953            print_name(out, "subject=", X509_get_subject_name(x509ss),
954                       nmflag);
955        else
956            print_name(out, "subject=", X509_REQ_get_subject_name(req),
957                       nmflag);
958    }
959
960    if (modulus) {
961        EVP_PKEY *tpubkey;
962
963        if (x509)
964            tpubkey = X509_get_pubkey(x509ss);
965        else
966            tpubkey = X509_REQ_get_pubkey(req);
967        if (tpubkey == NULL) {
968            fprintf(stdout, "Modulus=unavailable\n");
969            goto end;
970        }
971        fprintf(stdout, "Modulus=");
972#ifndef OPENSSL_NO_RSA
973        if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
974            BN_print(out, tpubkey->pkey.rsa->n);
975        else
976#endif
977            fprintf(stdout, "Wrong Algorithm type");
978        EVP_PKEY_free(tpubkey);
979        fprintf(stdout, "\n");
980    }
981
982    if (!noout && !x509) {
983        if (outformat == FORMAT_ASN1)
984            i = i2d_X509_REQ_bio(out, req);
985        else if (outformat == FORMAT_PEM) {
986            if (newhdr)
987                i = PEM_write_bio_X509_REQ_NEW(out, req);
988            else
989                i = PEM_write_bio_X509_REQ(out, req);
990        } else {
991            BIO_printf(bio_err, "bad output format specified for outfile\n");
992            goto end;
993        }
994        if (!i) {
995            BIO_printf(bio_err, "unable to write X509 request\n");
996            goto end;
997        }
998    }
999    if (!noout && x509 && (x509ss != NULL)) {
1000        if (outformat == FORMAT_ASN1)
1001            i = i2d_X509_bio(out, x509ss);
1002        else if (outformat == FORMAT_PEM)
1003            i = PEM_write_bio_X509(out, x509ss);
1004        else {
1005            BIO_printf(bio_err, "bad output format specified for outfile\n");
1006            goto end;
1007        }
1008        if (!i) {
1009            BIO_printf(bio_err, "unable to write X509 certificate\n");
1010            goto end;
1011        }
1012    }
1013    ex = 0;
1014 end:
1015#ifndef MONOLITH
1016    if (to_free)
1017        OPENSSL_free(to_free);
1018#endif
1019    if (ex) {
1020        ERR_print_errors(bio_err);
1021    }
1022    if ((req_conf != NULL) && (req_conf != config))
1023        NCONF_free(req_conf);
1024    BIO_free(in);
1025    BIO_free_all(out);
1026    EVP_PKEY_free(pkey);
1027    if (genctx)
1028        EVP_PKEY_CTX_free(genctx);
1029    if (pkeyopts)
1030        sk_OPENSSL_STRING_free(pkeyopts);
1031    if (sigopts)
1032        sk_OPENSSL_STRING_free(sigopts);
1033#ifndef OPENSSL_NO_ENGINE
1034    if (gen_eng)
1035        ENGINE_free(gen_eng);
1036#endif
1037    if (keyalgstr)
1038        OPENSSL_free(keyalgstr);
1039    X509_REQ_free(req);
1040    X509_free(x509ss);
1041    ASN1_INTEGER_free(serial);
1042    if (passargin && passin)
1043        OPENSSL_free(passin);
1044    if (passargout && passout)
1045        OPENSSL_free(passout);
1046    OBJ_cleanup();
1047    apps_shutdown();
1048    OPENSSL_EXIT(ex);
1049}
1050
1051static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1052                    int attribs, unsigned long chtype)
1053{
1054    int ret = 0, i;
1055    char no_prompt = 0;
1056    STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1057    char *tmp, *dn_sect, *attr_sect;
1058
1059    tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
1060    if (tmp == NULL)
1061        ERR_clear_error();
1062    if ((tmp != NULL) && !strcmp(tmp, "no"))
1063        no_prompt = 1;
1064
1065    dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
1066    if (dn_sect == NULL) {
1067        BIO_printf(bio_err, "unable to find '%s' in config\n",
1068                   DISTINGUISHED_NAME);
1069        goto err;
1070    }
1071    dn_sk = NCONF_get_section(req_conf, dn_sect);
1072    if (dn_sk == NULL) {
1073        BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1074        goto err;
1075    }
1076
1077    attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
1078    if (attr_sect == NULL) {
1079        ERR_clear_error();
1080        attr_sk = NULL;
1081    } else {
1082        attr_sk = NCONF_get_section(req_conf, attr_sect);
1083        if (attr_sk == NULL) {
1084            BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1085            goto err;
1086        }
1087    }
1088
1089    /* setup version number */
1090    if (!X509_REQ_set_version(req, 0L))
1091        goto err;               /* version 1 */
1092
1093    if (no_prompt)
1094        i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1095    else {
1096        if (subj)
1097            i = build_subject(req, subj, chtype, multirdn);
1098        else
1099            i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1100                            chtype);
1101    }
1102    if (!i)
1103        goto err;
1104
1105    if (!X509_REQ_set_pubkey(req, pkey))
1106        goto err;
1107
1108    ret = 1;
1109 err:
1110    return (ret);
1111}
1112
1113/*
1114 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1115 * where characters may be escaped by \
1116 */
1117static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
1118                         int multirdn)
1119{
1120    X509_NAME *n;
1121
1122    if (!(n = parse_name(subject, chtype, multirdn)))
1123        return 0;
1124
1125    if (!X509_REQ_set_subject_name(req, n)) {
1126        X509_NAME_free(n);
1127        return 0;
1128    }
1129    X509_NAME_free(n);
1130    return 1;
1131}
1132
1133static int prompt_info(X509_REQ *req,
1134                       STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
1135                       STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
1136                       int attribs, unsigned long chtype)
1137{
1138    int i;
1139    char *p, *q;
1140    char buf[100];
1141    int nid, mval;
1142    long n_min, n_max;
1143    char *type, *value;
1144    const char *def;
1145    CONF_VALUE *v;
1146    X509_NAME *subj;
1147    subj = X509_REQ_get_subject_name(req);
1148
1149    if (!batch) {
1150        BIO_printf(bio_err,
1151                   "You are about to be asked to enter information that will be incorporated\n");
1152        BIO_printf(bio_err, "into your certificate request.\n");
1153        BIO_printf(bio_err,
1154                   "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1155        BIO_printf(bio_err,
1156                   "There are quite a few fields but you can leave some blank\n");
1157        BIO_printf(bio_err,
1158                   "For some fields there will be a default value,\n");
1159        BIO_printf(bio_err,
1160                   "If you enter '.', the field will be left blank.\n");
1161        BIO_printf(bio_err, "-----\n");
1162    }
1163
1164    if (sk_CONF_VALUE_num(dn_sk)) {
1165        i = -1;
1166 start:for (;;) {
1167            i++;
1168            if (sk_CONF_VALUE_num(dn_sk) <= i)
1169                break;
1170
1171            v = sk_CONF_VALUE_value(dn_sk, i);
1172            p = q = NULL;
1173            type = v->name;
1174            if (!check_end(type, "_min") || !check_end(type, "_max") ||
1175                !check_end(type, "_default") || !check_end(type, "_value"))
1176                continue;
1177            /*
1178             * Skip past any leading X. X: X, etc to allow for multiple
1179             * instances
1180             */
1181            for (p = v->name; *p; p++)
1182                if ((*p == ':') || (*p == ',') || (*p == '.')) {
1183                    p++;
1184                    if (*p)
1185                        type = p;
1186                    break;
1187                }
1188            if (*type == '+') {
1189                mval = -1;
1190                type++;
1191            } else
1192                mval = 0;
1193            /* If OBJ not recognised ignore it */
1194            if ((nid = OBJ_txt2nid(type)) == NID_undef)
1195                goto start;
1196            if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
1197                >= (int)sizeof(buf)) {
1198                BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1199                return 0;
1200            }
1201
1202            if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1203                ERR_clear_error();
1204                def = "";
1205            }
1206
1207            BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
1208            if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1209                ERR_clear_error();
1210                value = NULL;
1211            }
1212
1213            BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1214            if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1215                ERR_clear_error();
1216                n_min = -1;
1217            }
1218
1219            BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1220            if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1221                ERR_clear_error();
1222                n_max = -1;
1223            }
1224
1225            if (!add_DN_object(subj, v->value, def, value, nid,
1226                               n_min, n_max, chtype, mval))
1227                return 0;
1228        }
1229        if (X509_NAME_entry_count(subj) == 0) {
1230            BIO_printf(bio_err,
1231                       "error, no objects specified in config file\n");
1232            return 0;
1233        }
1234
1235        if (attribs) {
1236            if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1237                && (!batch)) {
1238                BIO_printf(bio_err,
1239                           "\nPlease enter the following 'extra' attributes\n");
1240                BIO_printf(bio_err,
1241                           "to be sent with your certificate request\n");
1242            }
1243
1244            i = -1;
1245 start2:   for (;;) {
1246                i++;
1247                if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1248                    break;
1249
1250                v = sk_CONF_VALUE_value(attr_sk, i);
1251                type = v->name;
1252                if ((nid = OBJ_txt2nid(type)) == NID_undef)
1253                    goto start2;
1254
1255                if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1256                    >= (int)sizeof(buf)) {
1257                    BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1258                    return 0;
1259                }
1260
1261                if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1262                    == NULL) {
1263                    ERR_clear_error();
1264                    def = "";
1265                }
1266
1267                BIO_snprintf(buf, sizeof buf, "%s_value", type);
1268                if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1269                    == NULL) {
1270                    ERR_clear_error();
1271                    value = NULL;
1272                }
1273
1274                BIO_snprintf(buf, sizeof buf, "%s_min", type);
1275                if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1276                    ERR_clear_error();
1277                    n_min = -1;
1278                }
1279
1280                BIO_snprintf(buf, sizeof buf, "%s_max", type);
1281                if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1282                    ERR_clear_error();
1283                    n_max = -1;
1284                }
1285
1286                if (!add_attribute_object(req,
1287                                          v->value, def, value, nid, n_min,
1288                                          n_max, chtype))
1289                    return 0;
1290            }
1291        }
1292    } else {
1293        BIO_printf(bio_err, "No template, please set one up.\n");
1294        return 0;
1295    }
1296
1297    return 1;
1298
1299}
1300
1301static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1302                     STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1303                     unsigned long chtype)
1304{
1305    int i;
1306    char *p, *q;
1307    char *type;
1308    CONF_VALUE *v;
1309    X509_NAME *subj;
1310
1311    subj = X509_REQ_get_subject_name(req);
1312
1313    for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1314        int mval;
1315        v = sk_CONF_VALUE_value(dn_sk, i);
1316        p = q = NULL;
1317        type = v->name;
1318        /*
1319         * Skip past any leading X. X: X, etc to allow for multiple instances
1320         */
1321        for (p = v->name; *p; p++)
1322#ifndef CHARSET_EBCDIC
1323            if ((*p == ':') || (*p == ',') || (*p == '.')) {
1324#else
1325            if ((*p == os_toascii[':']) || (*p == os_toascii[','])
1326                || (*p == os_toascii['.'])) {
1327#endif
1328                p++;
1329                if (*p)
1330                    type = p;
1331                break;
1332            }
1333#ifndef CHARSET_EBCDIC
1334        if (*p == '+')
1335#else
1336        if (*p == os_toascii['+'])
1337#endif
1338        {
1339            p++;
1340            mval = -1;
1341        } else
1342            mval = 0;
1343        if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1344                                        (unsigned char *)v->value, -1, -1,
1345                                        mval))
1346            return 0;
1347
1348    }
1349
1350    if (!X509_NAME_entry_count(subj)) {
1351        BIO_printf(bio_err, "error, no objects specified in config file\n");
1352        return 0;
1353    }
1354    if (attribs) {
1355        for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1356            v = sk_CONF_VALUE_value(attr_sk, i);
1357            if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1358                                           (unsigned char *)v->value, -1))
1359                return 0;
1360        }
1361    }
1362    return 1;
1363}
1364
1365static int add_DN_object(X509_NAME *n, char *text, const char *def,
1366                         char *value, int nid, int n_min, int n_max,
1367                         unsigned long chtype, int mval)
1368{
1369    int i, ret = 0;
1370    MS_STATIC char buf[1024];
1371 start:
1372    if (!batch)
1373        BIO_printf(bio_err, "%s [%s]:", text, def);
1374    (void)BIO_flush(bio_err);
1375    if (value != NULL) {
1376        BUF_strlcpy(buf, value, sizeof buf);
1377        BUF_strlcat(buf, "\n", sizeof buf);
1378        BIO_printf(bio_err, "%s\n", value);
1379    } else {
1380        buf[0] = '\0';
1381        if (!batch) {
1382            if (!fgets(buf, sizeof buf, stdin))
1383                return 0;
1384        } else {
1385            buf[0] = '\n';
1386            buf[1] = '\0';
1387        }
1388    }
1389
1390    if (buf[0] == '\0')
1391        return (0);
1392    else if (buf[0] == '\n') {
1393        if ((def == NULL) || (def[0] == '\0'))
1394            return (1);
1395        BUF_strlcpy(buf, def, sizeof buf);
1396        BUF_strlcat(buf, "\n", sizeof buf);
1397    } else if ((buf[0] == '.') && (buf[1] == '\n'))
1398        return (1);
1399
1400    i = strlen(buf);
1401    if (buf[i - 1] != '\n') {
1402        BIO_printf(bio_err, "weird input :-(\n");
1403        return (0);
1404    }
1405    buf[--i] = '\0';
1406#ifdef CHARSET_EBCDIC
1407    ebcdic2ascii(buf, buf, i);
1408#endif
1409    if (!req_check_len(i, n_min, n_max)) {
1410        if (batch || value)
1411            return 0;
1412        goto start;
1413    }
1414
1415    if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1416                                    (unsigned char *)buf, -1, -1, mval))
1417        goto err;
1418    ret = 1;
1419 err:
1420    return (ret);
1421}
1422
1423static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1424                                char *value, int nid, int n_min,
1425                                int n_max, unsigned long chtype)
1426{
1427    int i;
1428    static char buf[1024];
1429
1430 start:
1431    if (!batch)
1432        BIO_printf(bio_err, "%s [%s]:", text, def);
1433    (void)BIO_flush(bio_err);
1434    if (value != NULL) {
1435        BUF_strlcpy(buf, value, sizeof buf);
1436        BUF_strlcat(buf, "\n", sizeof buf);
1437        BIO_printf(bio_err, "%s\n", value);
1438    } else {
1439        buf[0] = '\0';
1440        if (!batch) {
1441            if (!fgets(buf, sizeof buf, stdin))
1442                return 0;
1443        } else {
1444            buf[0] = '\n';
1445            buf[1] = '\0';
1446        }
1447    }
1448
1449    if (buf[0] == '\0')
1450        return (0);
1451    else if (buf[0] == '\n') {
1452        if ((def == NULL) || (def[0] == '\0'))
1453            return (1);
1454        BUF_strlcpy(buf, def, sizeof buf);
1455        BUF_strlcat(buf, "\n", sizeof buf);
1456    } else if ((buf[0] == '.') && (buf[1] == '\n'))
1457        return (1);
1458
1459    i = strlen(buf);
1460    if (buf[i - 1] != '\n') {
1461        BIO_printf(bio_err, "weird input :-(\n");
1462        return (0);
1463    }
1464    buf[--i] = '\0';
1465#ifdef CHARSET_EBCDIC
1466    ebcdic2ascii(buf, buf, i);
1467#endif
1468    if (!req_check_len(i, n_min, n_max)) {
1469        if (batch || value)
1470            return 0;
1471        goto start;
1472    }
1473
1474    if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1475                                   (unsigned char *)buf, -1)) {
1476        BIO_printf(bio_err, "Error adding attribute\n");
1477        ERR_print_errors(bio_err);
1478        goto err;
1479    }
1480
1481    return (1);
1482 err:
1483    return (0);
1484}
1485
1486static int req_check_len(int len, int n_min, int n_max)
1487{
1488    if ((n_min > 0) && (len < n_min)) {
1489        BIO_printf(bio_err,
1490                   "string is too short, it needs to be at least %d bytes long\n",
1491                   n_min);
1492        return (0);
1493    }
1494    if ((n_max >= 0) && (len > n_max)) {
1495        BIO_printf(bio_err,
1496                   "string is too long, it needs to be less than  %d bytes long\n",
1497                   n_max);
1498        return (0);
1499    }
1500    return (1);
1501}
1502
1503/* Check if the end of a string matches 'end' */
1504static int check_end(const char *str, const char *end)
1505{
1506    int elen, slen;
1507    const char *tmp;
1508    elen = strlen(end);
1509    slen = strlen(str);
1510    if (elen > slen)
1511        return 1;
1512    tmp = str + slen - elen;
1513    return strcmp(tmp, end);
1514}
1515
1516static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr,
1517                                    int *pkey_type, long *pkeylen,
1518                                    char **palgnam, ENGINE *keygen_engine)
1519{
1520    EVP_PKEY_CTX *gctx = NULL;
1521    EVP_PKEY *param = NULL;
1522    long keylen = -1;
1523    BIO *pbio = NULL;
1524    const char *paramfile = NULL;
1525
1526    if (gstr == NULL) {
1527        *pkey_type = EVP_PKEY_RSA;
1528        keylen = *pkeylen;
1529    } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1530        *pkey_type = EVP_PKEY_RSA;
1531        keylen = atol(gstr);
1532        *pkeylen = keylen;
1533    } else if (!strncmp(gstr, "param:", 6))
1534        paramfile = gstr + 6;
1535    else {
1536        const char *p = strchr(gstr, ':');
1537        int len;
1538        ENGINE *tmpeng;
1539        const EVP_PKEY_ASN1_METHOD *ameth;
1540
1541        if (p)
1542            len = p - gstr;
1543        else
1544            len = strlen(gstr);
1545        /*
1546         * The lookup of a the string will cover all engines so keep a note
1547         * of the implementation.
1548         */
1549
1550        ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1551
1552        if (!ameth) {
1553            BIO_printf(err, "Unknown algorithm %.*s\n", len, gstr);
1554            return NULL;
1555        }
1556
1557        EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1558#ifndef OPENSSL_NO_ENGINE
1559        if (tmpeng)
1560            ENGINE_finish(tmpeng);
1561#endif
1562        if (*pkey_type == EVP_PKEY_RSA) {
1563            if (p) {
1564                keylen = atol(p + 1);
1565                *pkeylen = keylen;
1566            } else
1567                keylen = *pkeylen;
1568        } else if (p)
1569            paramfile = p + 1;
1570    }
1571
1572    if (paramfile) {
1573        pbio = BIO_new_file(paramfile, "r");
1574        if (!pbio) {
1575            BIO_printf(err, "Can't open parameter file %s\n", paramfile);
1576            return NULL;
1577        }
1578        param = PEM_read_bio_Parameters(pbio, NULL);
1579
1580        if (!param) {
1581            X509 *x;
1582            (void)BIO_reset(pbio);
1583            x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1584            if (x) {
1585                param = X509_get_pubkey(x);
1586                X509_free(x);
1587            }
1588        }
1589
1590        BIO_free(pbio);
1591
1592        if (!param) {
1593            BIO_printf(err, "Error reading parameter file %s\n", paramfile);
1594            return NULL;
1595        }
1596        if (*pkey_type == -1)
1597            *pkey_type = EVP_PKEY_id(param);
1598        else if (*pkey_type != EVP_PKEY_base_id(param)) {
1599            BIO_printf(err, "Key Type does not match parameters\n");
1600            EVP_PKEY_free(param);
1601            return NULL;
1602        }
1603    }
1604
1605    if (palgnam) {
1606        const EVP_PKEY_ASN1_METHOD *ameth;
1607        ENGINE *tmpeng;
1608        const char *anam;
1609        ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1610        if (!ameth) {
1611            BIO_puts(err, "Internal error: can't find key algorithm\n");
1612            return NULL;
1613        }
1614        EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1615        *palgnam = BUF_strdup(anam);
1616#ifndef OPENSSL_NO_ENGINE
1617        if (tmpeng)
1618            ENGINE_finish(tmpeng);
1619#endif
1620    }
1621
1622    if (param) {
1623        gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1624        *pkeylen = EVP_PKEY_bits(param);
1625        EVP_PKEY_free(param);
1626    } else
1627        gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1628
1629    if (!gctx) {
1630        BIO_puts(err, "Error allocating keygen context\n");
1631        ERR_print_errors(err);
1632        return NULL;
1633    }
1634
1635    if (EVP_PKEY_keygen_init(gctx) <= 0) {
1636        BIO_puts(err, "Error initializing keygen context\n");
1637        ERR_print_errors(err);
1638        return NULL;
1639    }
1640#ifndef OPENSSL_NO_RSA
1641    if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1642        if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1643            BIO_puts(err, "Error setting RSA keysize\n");
1644            ERR_print_errors(err);
1645            EVP_PKEY_CTX_free(gctx);
1646            return NULL;
1647        }
1648    }
1649#endif
1650
1651    return gctx;
1652}
1653
1654static int genpkey_cb(EVP_PKEY_CTX *ctx)
1655{
1656    char c = '*';
1657    BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1658    int p;
1659    p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1660    if (p == 0)
1661        c = '.';
1662    if (p == 1)
1663        c = '+';
1664    if (p == 2)
1665        c = '*';
1666    if (p == 3)
1667        c = '\n';
1668    BIO_write(b, &c, 1);
1669    (void)BIO_flush(b);
1670#ifdef LINT
1671    p = n;
1672#endif
1673    return 1;
1674}
1675
1676static int do_sign_init(BIO *err, EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1677                        const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1678{
1679    EVP_PKEY_CTX *pkctx = NULL;
1680    int i;
1681    EVP_MD_CTX_init(ctx);
1682    if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1683        return 0;
1684    for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1685        char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1686        if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1687            BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1688            ERR_print_errors(bio_err);
1689            return 0;
1690        }
1691    }
1692    return 1;
1693}
1694
1695int do_X509_sign(BIO *err, X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1696                 STACK_OF(OPENSSL_STRING) *sigopts)
1697{
1698    int rv;
1699    EVP_MD_CTX mctx;
1700    EVP_MD_CTX_init(&mctx);
1701    rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1702    if (rv > 0)
1703        rv = X509_sign_ctx(x, &mctx);
1704    EVP_MD_CTX_cleanup(&mctx);
1705    return rv > 0 ? 1 : 0;
1706}
1707
1708int do_X509_REQ_sign(BIO *err, X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1709                     STACK_OF(OPENSSL_STRING) *sigopts)
1710{
1711    int rv;
1712    EVP_MD_CTX mctx;
1713    EVP_MD_CTX_init(&mctx);
1714    rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1715    if (rv > 0)
1716        rv = X509_REQ_sign_ctx(x, &mctx);
1717    EVP_MD_CTX_cleanup(&mctx);
1718    return rv > 0 ? 1 : 0;
1719}
1720
1721int do_X509_CRL_sign(BIO *err, X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1722                     STACK_OF(OPENSSL_STRING) *sigopts)
1723{
1724    int rv;
1725    EVP_MD_CTX mctx;
1726    EVP_MD_CTX_init(&mctx);
1727    rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1728    if (rv > 0)
1729        rv = X509_CRL_sign_ctx(x, &mctx);
1730    EVP_MD_CTX_cleanup(&mctx);
1731    return rv > 0 ? 1 : 0;
1732}
1733