APPS/req: Fix AKID generation in case -CA option is used
[openssl.git] / apps / req.c
1 /*
2  * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <time.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include "apps.h"
16 #include "progs.h"
17 #include <openssl/core_names.h>
18 #include <openssl/bio.h>
19 #include <openssl/evp.h>
20 #include <openssl/conf.h>
21 #include <openssl/err.h>
22 #include <openssl/asn1.h>
23 #include <openssl/x509.h>
24 #include <openssl/x509v3.h>
25 #include <openssl/objects.h>
26 #include <openssl/pem.h>
27 #include <openssl/bn.h>
28 #include <openssl/lhash.h>
29 #include <openssl/rsa.h>
30 #ifndef OPENSSL_NO_DSA
31 # include <openssl/dsa.h>
32 #endif
33
34 #define BITS               "default_bits"
35 #define KEYFILE            "default_keyfile"
36 #define PROMPT             "prompt"
37 #define DISTINGUISHED_NAME "distinguished_name"
38 #define ATTRIBUTES         "attributes"
39 #define V3_EXTENSIONS      "x509_extensions"
40 #define REQ_EXTENSIONS     "req_extensions"
41 #define STRING_MASK        "string_mask"
42 #define UTF8_IN            "utf8"
43
44 #define DEFAULT_KEY_LENGTH 2048
45 #define MIN_KEY_LENGTH     512
46 #define DEFAULT_DAYS       30 /* default cert validity period in days */
47 #define UNSET_DAYS         -2 /* -1 may be used for testing expiration checks */
48 #define EXT_COPY_UNSET     -1
49
50 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
51                     int mutlirdn, int attribs, unsigned long chtype);
52 static int prompt_info(X509_REQ *req,
53                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
54                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
55                        int attribs, unsigned long chtype);
56 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
57                      STACK_OF(CONF_VALUE) *attr, int attribs,
58                      unsigned long chtype);
59 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
60                                 char *value, int nid, int n_min, int n_max,
61                                 unsigned long chtype);
62 static int add_DN_object(X509_NAME *n, char *text, const char *def,
63                          char *value, int nid, int n_min, int n_max,
64                          unsigned long chtype, int mval);
65 static int genpkey_cb(EVP_PKEY_CTX *ctx);
66 static int build_data(char *text, const char *def, char *value,
67                       int n_min, int n_max, char *buf, const int buf_size,
68                       const char *desc1, const char *desc2);
69 static int req_check_len(int len, int n_min, int n_max);
70 static int check_end(const char *str, const char *end);
71 static int join(char buf[], size_t buf_size, const char *name,
72                 const char *tail, const char *desc);
73 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
74                                     char **pkeytype, long *pkeylen,
75                                     ENGINE *keygen_engine);
76
77 static const char *section = "req";
78 static CONF *req_conf = NULL;
79 static CONF *addext_conf = NULL;
80 static int batch = 0;
81
82 typedef enum OPTION_choice {
83     OPT_COMMON,
84     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
85     OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
86     OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
87     OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
88     OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
89     OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
90     OPT_CA, OPT_CAKEY,
91     OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL,
92     OPT_COPY_EXTENSIONS, OPT_ADDEXT, OPT_EXTENSIONS,
93     OPT_REQEXTS, OPT_PRECERT, OPT_MD,
94     OPT_SECTION,
95     OPT_R_ENUM, OPT_PROV_ENUM
96 } OPTION_CHOICE;
97
98 const OPTIONS req_options[] = {
99     OPT_SECTION("General"),
100     {"help", OPT_HELP, '-', "Display this summary"},
101 #ifndef OPENSSL_NO_ENGINE
102     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
103     {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
104      "Specify engine to be used for key generation operations"},
105 #endif
106     {"in", OPT_IN, '<', "X.509 request input file"},
107     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
108     {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"},
109
110     OPT_SECTION("Certificate"),
111     {"new", OPT_NEW, '-', "New request"},
112     {"config", OPT_CONFIG, '<', "Request template file"},
113     {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
114     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
115     {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
116     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
117     {"text", OPT_TEXT, '-', "Text form of request"},
118     {"x509", OPT_X509, '-',
119      "Output an X.509 certificate structure instead of a cert request"},
120     {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"},
121     {"CAkey", OPT_CAKEY, 's',
122      "Issuer private key to use with -CA; default is -CA arg"},
123     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
124     {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
125     {"subject", OPT_SUBJECT, '-',
126      "Print the subject of the output request or cert"},
127     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
128      "Deprecated; multi-valued RDNs support is always on."},
129     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
130     {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
131     {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
132      "copy extensions from request when using -x509"},
133     {"addext", OPT_ADDEXT, 's',
134      "Additional cert extension key=value pair (may be given more than once)"},
135     {"extensions", OPT_EXTENSIONS, 's',
136      "Cert extension section (override value in config file)"},
137     {"reqexts", OPT_REQEXTS, 's',
138      "Request extension section (override value in config file)"},
139     {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
140
141     OPT_SECTION("Keys and Signing"),
142     {"key", OPT_KEY, 's', "Key to include and to use for self-signature"},
143     {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
144     {"pubkey", OPT_PUBKEY, '-', "Output public key"},
145     {"keyout", OPT_KEYOUT, '>', "File to write private key to"},
146     {"passin", OPT_PASSIN, 's', "Private key and certificate password source"},
147     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
148     {"newkey", OPT_NEWKEY, 's',
149      "Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"},
150     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
151     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
152     {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
153     {"", OPT_MD, '-', "Any supported digest"},
154
155     OPT_SECTION("Output"),
156     {"out", OPT_OUT, '>', "Output file"},
157     {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
158     {"batch", OPT_BATCH, '-',
159      "Do not ask anything during request generation"},
160     {"verbose", OPT_VERBOSE, '-', "Verbose output"},
161     {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
162     {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
163     {"noout", OPT_NOOUT, '-', "Do not output REQ"},
164     {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
165     {"modulus", OPT_MODULUS, '-', "RSA modulus"},
166
167     OPT_R_OPTIONS,
168     OPT_PROV_OPTIONS,
169     {NULL}
170 };
171
172 /*
173  * An LHASH of strings, where each string is an extension name.
174  */
175 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
176 {
177     return OPENSSL_LH_strhash((const char *)a);
178 }
179
180 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
181 {
182     return strcmp((const char *)a, (const char *)b);
183 }
184
185 static void exts_cleanup(OPENSSL_STRING *x)
186 {
187     OPENSSL_free((char *)x);
188 }
189
190 /*
191  * Is the |kv| key already duplicated? This is remarkably tricky to get right.
192  * Return 0 if unique, -1 on runtime error; 1 if found or a syntax error.
193  */
194 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
195 {
196     char *p;
197     size_t off;
198
199     /* Check syntax. */
200     /* Skip leading whitespace, make a copy. */
201     while (*kv && isspace(*kv))
202         if (*++kv == '\0')
203             return 1;
204     if ((p = strchr(kv, '=')) == NULL)
205         return 1;
206     off = p - kv;
207     if ((kv = OPENSSL_strdup(kv)) == NULL)
208         return -1;
209
210     /* Skip trailing space before the equal sign. */
211     for (p = kv + off; p > kv; --p)
212         if (!isspace(p[-1]))
213             break;
214     if (p == kv) {
215         OPENSSL_free(kv);
216         return 1;
217     }
218     *p = '\0';
219
220     /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
221     p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv);
222     if (p != NULL) {
223         OPENSSL_free(p);
224         return 1;
225     } else if (lh_OPENSSL_STRING_error(addexts)) {
226         OPENSSL_free(kv);
227         return -1;
228     }
229
230     return 0;
231 }
232
233 int req_main(int argc, char **argv)
234 {
235     ASN1_INTEGER *serial = NULL;
236     BIO *out = NULL;
237     ENGINE *e = NULL, *gen_eng = NULL;
238     EVP_PKEY *pkey = NULL, *CAkey = NULL;
239     EVP_PKEY_CTX *genctx = NULL;
240     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
241     LHASH_OF(OPENSSL_STRING) *addexts = NULL;
242     X509 *new_x509 = NULL, *CAcert = NULL;
243     X509_REQ *req = NULL;
244     EVP_CIPHER *cipher = NULL;
245     EVP_MD *md = NULL;
246     int ext_copy = EXT_COPY_UNSET;
247     BIO *addext_bio = NULL;
248     char *extensions = NULL;
249     const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL;
250     char *outfile = NULL, *keyfile = NULL, *digest = NULL;
251     char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
252     char *passin = NULL, *passout = NULL;
253     char *nofree_passin = NULL, *nofree_passout = NULL;
254     char *req_exts = NULL, *subj = NULL;
255     X509_NAME *fsubj = NULL;
256     char *template = default_config_file, *keyout = NULL;
257     const char *keyalg = NULL;
258     OPTION_CHOICE o;
259     int days = UNSET_DAYS;
260     int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0;
261     int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF;
262     int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
263     int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
264     long newkey_len = -1;
265     unsigned long chtype = MBSTRING_ASC, reqflag = 0;
266
267 #ifndef OPENSSL_NO_DES
268     cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
269 #endif
270
271     prog = opt_init(argc, argv, req_options);
272     while ((o = opt_next()) != OPT_EOF) {
273         switch (o) {
274         case OPT_EOF:
275         case OPT_ERR:
276  opthelp:
277             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
278             goto end;
279         case OPT_HELP:
280             opt_help(req_options);
281             ret = 0;
282             goto end;
283         case OPT_INFORM:
284             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
285                 goto opthelp;
286             break;
287         case OPT_OUTFORM:
288             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
289                 goto opthelp;
290             break;
291         case OPT_ENGINE:
292             e = setup_engine(opt_arg(), 0);
293             break;
294         case OPT_KEYGEN_ENGINE:
295 #ifndef OPENSSL_NO_ENGINE
296             gen_eng = setup_engine(opt_arg(), 0);
297             if (gen_eng == NULL) {
298                 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
299                 goto opthelp;
300             }
301 #endif
302             break;
303         case OPT_KEY:
304             keyfile = opt_arg();
305             break;
306         case OPT_PUBKEY:
307             pubkey = 1;
308             break;
309         case OPT_NEW:
310             newreq = 1;
311             break;
312         case OPT_CONFIG:
313             template = opt_arg();
314             break;
315         case OPT_SECTION:
316             section = opt_arg();
317             break;
318         case OPT_KEYFORM:
319             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
320                 goto opthelp;
321             break;
322         case OPT_IN:
323             infile = opt_arg();
324             break;
325         case OPT_OUT:
326             outfile = opt_arg();
327             break;
328         case OPT_KEYOUT:
329             keyout = opt_arg();
330             break;
331         case OPT_PASSIN:
332             passargin = opt_arg();
333             break;
334         case OPT_PASSOUT:
335             passargout = opt_arg();
336             break;
337         case OPT_R_CASES:
338             if (!opt_rand(o))
339                 goto end;
340             break;
341         case OPT_PROV_CASES:
342             if (!opt_provider(o))
343                 goto end;
344             break;
345         case OPT_NEWKEY:
346             keyalg = opt_arg();
347             newreq = 1;
348             break;
349         case OPT_PKEYOPT:
350             if (pkeyopts == NULL)
351                 pkeyopts = sk_OPENSSL_STRING_new_null();
352             if (pkeyopts == NULL
353                     || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
354                 goto opthelp;
355             break;
356         case OPT_SIGOPT:
357             if (!sigopts)
358                 sigopts = sk_OPENSSL_STRING_new_null();
359             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
360                 goto opthelp;
361             break;
362         case OPT_VFYOPT:
363             if (!vfyopts)
364                 vfyopts = sk_OPENSSL_STRING_new_null();
365             if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
366                 goto opthelp;
367             break;
368         case OPT_BATCH:
369             batch = 1;
370             break;
371         case OPT_NEWHDR:
372             newhdr = 1;
373             break;
374         case OPT_MODULUS:
375             modulus = 1;
376             break;
377         case OPT_VERIFY:
378             verify = 1;
379             break;
380         case OPT_NODES:
381         case OPT_NOENC:
382             noenc = 1;
383             break;
384         case OPT_NOOUT:
385             noout = 1;
386             break;
387         case OPT_VERBOSE:
388             verbose = 1;
389             break;
390         case OPT_UTF8:
391             chtype = MBSTRING_UTF8;
392             break;
393         case OPT_NAMEOPT:
394             if (!set_nameopt(opt_arg()))
395                 goto opthelp;
396             break;
397         case OPT_REQOPT:
398             if (!set_cert_ex(&reqflag, opt_arg()))
399                 goto opthelp;
400             break;
401         case OPT_TEXT:
402             text = 1;
403             break;
404         case OPT_X509:
405             gen_x509 = 1;
406             break;
407         case OPT_CA:
408             CAfile = opt_arg();
409             gen_x509 = 1;
410             break;
411         case OPT_CAKEY:
412             CAkeyfile = opt_arg();
413             break;
414         case OPT_DAYS:
415             days = atoi(opt_arg());
416             if (days < -1) {
417                 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
418                            prog);
419                 goto end;
420             }
421             break;
422         case OPT_SET_SERIAL:
423             if (serial != NULL) {
424                 BIO_printf(bio_err, "Serial number supplied twice\n");
425                 goto opthelp;
426             }
427             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
428             if (serial == NULL)
429                 goto opthelp;
430             break;
431         case OPT_SUBJECT:
432             subject = 1;
433             break;
434         case OPT_SUBJ:
435             subj = opt_arg();
436             break;
437         case OPT_MULTIVALUE_RDN:
438             /* obsolete */
439             break;
440         case OPT_COPY_EXTENSIONS:
441             if (!set_ext_copy(&ext_copy, opt_arg())) {
442                 BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
443                            opt_arg());
444                 goto end;
445             }
446             break;
447         case OPT_ADDEXT:
448             p = opt_arg();
449             if (addexts == NULL) {
450                 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
451                 addext_bio = BIO_new(BIO_s_mem());
452                 if (addexts == NULL || addext_bio == NULL)
453                     goto end;
454             }
455             i = duplicated(addexts, p);
456             if (i == 1) {
457                 BIO_printf(bio_err, "Duplicate extension: %s\n", p);
458                 goto opthelp;
459             }
460             if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
461                 goto end;
462             break;
463         case OPT_EXTENSIONS:
464             extensions = opt_arg();
465             break;
466         case OPT_REQEXTS:
467             req_exts = opt_arg();
468             break;
469         case OPT_PRECERT:
470             newreq = precert = 1;
471             break;
472         case OPT_MD:
473             digest = opt_unknown();
474             break;
475         }
476     }
477
478     /* No extra arguments. */
479     argc = opt_num_rest();
480     if (argc != 0)
481         goto opthelp;
482
483     if (!app_RAND_load())
484         goto end;
485
486     if (!gen_x509) {
487         if (days != UNSET_DAYS)
488             BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
489         if (ext_copy == EXT_COPY_NONE)
490             BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
491     }
492     if (gen_x509 && infile == NULL)
493         newreq = 1;
494
495     if (!app_passwd(passargin, passargout, &passin, &passout)) {
496         BIO_printf(bio_err, "Error getting passwords\n");
497         goto end;
498     }
499
500     if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
501         goto end;
502     if (addext_bio != NULL) {
503         if (verbose)
504             BIO_printf(bio_err,
505                        "Using additional configuration from -addext options\n");
506         if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
507             goto end;
508     }
509     if (template != default_config_file && !app_load_modules(req_conf))
510         goto end;
511
512     if (req_conf != NULL) {
513         p = NCONF_get_string(req_conf, NULL, "oid_file");
514         if (p == NULL)
515             ERR_clear_error();
516         if (p != NULL) {
517             BIO *oid_bio = BIO_new_file(p, "r");
518
519             if (oid_bio == NULL) {
520                 if (verbose)
521                     BIO_printf(bio_err,
522                                "Problems opening '%s' for extra OIDs\n", p);
523             } else {
524                 OBJ_create_objects(oid_bio);
525                 BIO_free(oid_bio);
526             }
527         }
528     }
529     if (!add_oid_section(req_conf))
530         goto end;
531
532     /* Check that any specified digest is fetchable */
533     if (digest != NULL) {
534         if (!opt_md(digest, &md)) {
535             ERR_clear_error();
536             goto opthelp;
537         }
538         EVP_MD_free(md);
539     } else {
540         /* No digest specified, default to configuration */
541         p = NCONF_get_string(req_conf, section, "default_md");
542         if (p == NULL)
543             ERR_clear_error();
544         else
545             digest = p;
546     }
547
548     if (extensions == NULL) {
549         extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
550         if (extensions == NULL)
551             ERR_clear_error();
552     }
553     if (extensions != NULL) {
554         /* Check syntax of file */
555         X509V3_CTX ctx;
556
557         X509V3_set_ctx_test(&ctx);
558         X509V3_set_nconf(&ctx, req_conf);
559         if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
560             BIO_printf(bio_err,
561                        "Error checking x509 extension section %s\n",
562                        extensions);
563             goto end;
564         }
565     }
566     if (addext_conf != NULL) {
567         /* Check syntax of command line extensions */
568         X509V3_CTX ctx;
569
570         X509V3_set_ctx_test(&ctx);
571         X509V3_set_nconf(&ctx, addext_conf);
572         if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
573             BIO_printf(bio_err, "Error checking extensions defined using -addext\n");
574             goto end;
575         }
576     }
577
578     if (passin == NULL) {
579         passin = nofree_passin =
580             NCONF_get_string(req_conf, section, "input_password");
581         if (passin == NULL)
582             ERR_clear_error();
583     }
584
585     if (passout == NULL) {
586         passout = nofree_passout =
587             NCONF_get_string(req_conf, section, "output_password");
588         if (passout == NULL)
589             ERR_clear_error();
590     }
591
592     p = NCONF_get_string(req_conf, section, STRING_MASK);
593     if (p == NULL)
594         ERR_clear_error();
595
596     if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
597         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
598         goto end;
599     }
600
601     if (chtype != MBSTRING_UTF8) {
602         p = NCONF_get_string(req_conf, section, UTF8_IN);
603         if (p == NULL)
604             ERR_clear_error();
605         else if (strcmp(p, "yes") == 0)
606             chtype = MBSTRING_UTF8;
607     }
608
609     if (req_exts == NULL) {
610         req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
611         if (req_exts == NULL)
612             ERR_clear_error();
613     }
614     if (req_exts != NULL) {
615         /* Check syntax of file */
616         X509V3_CTX ctx;
617
618         X509V3_set_ctx_test(&ctx);
619         X509V3_set_nconf(&ctx, req_conf);
620         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
621             BIO_printf(bio_err,
622                        "Error checking request extension section %s\n",
623                        req_exts);
624             goto end;
625         }
626     }
627
628     if (keyfile != NULL) {
629         pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
630         if (pkey == NULL)
631             goto end;
632         app_RAND_load_conf(req_conf, section);
633     }
634     if (newreq && pkey == NULL) {
635         app_RAND_load_conf(req_conf, section);
636
637         if (!NCONF_get_number(req_conf, section, BITS, &newkey_len))
638             newkey_len = DEFAULT_KEY_LENGTH;
639
640         genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng);
641         if (genctx == NULL)
642             goto end;
643
644         if (newkey_len < MIN_KEY_LENGTH
645             && (EVP_PKEY_CTX_is_a(genctx, "RSA")
646                 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")
647                 || EVP_PKEY_CTX_is_a(genctx, "DSA"))) {
648             BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n",
649                        MIN_KEY_LENGTH, newkey_len);
650             goto end;
651         }
652
653         if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS
654             && (EVP_PKEY_CTX_is_a(genctx, "RSA")
655                 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")))
656             BIO_printf(bio_err,
657                        "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
658                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
659                        OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
660
661 #ifndef OPENSSL_NO_DSA
662         if (EVP_PKEY_CTX_is_a(genctx, "DSA")
663                 && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
664             BIO_printf(bio_err,
665                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
666                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
667                        OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
668 #endif
669
670         if (pkeyopts != NULL) {
671             char *genopt;
672             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
673                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
674                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
675                     BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
676                     goto end;
677                 }
678             }
679         }
680
681         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
682         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
683
684         pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose);
685
686         EVP_PKEY_CTX_free(genctx);
687         genctx = NULL;
688     }
689     if (keyout == NULL && keyfile == NULL) {
690         keyout = NCONF_get_string(req_conf, section, KEYFILE);
691         if (keyout == NULL)
692             ERR_clear_error();
693     }
694
695     if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
696         if (verbose) {
697             BIO_printf(bio_err, "Writing private key to ");
698             if (keyout == NULL)
699                 BIO_printf(bio_err, "stdout\n");
700             else
701                 BIO_printf(bio_err, "'%s'\n", keyout);
702         }
703         out = bio_open_owner(keyout, outformat, newreq);
704         if (out == NULL)
705             goto end;
706
707         p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
708         if (p == NULL) {
709             ERR_clear_error();
710             p = NCONF_get_string(req_conf, section, "encrypt_key");
711             if (p == NULL)
712                 ERR_clear_error();
713         }
714         if ((p != NULL) && (strcmp(p, "no") == 0))
715             cipher = NULL;
716         if (noenc)
717             cipher = NULL;
718
719         i = 0;
720  loop:
721         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
722                                       NULL, 0, NULL, passout)) {
723             if ((ERR_GET_REASON(ERR_peek_error()) ==
724                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
725                 ERR_clear_error();
726                 i++;
727                 goto loop;
728             }
729             goto end;
730         }
731         BIO_free(out);
732         out = NULL;
733         BIO_printf(bio_err, "-----\n");
734     }
735
736     /*
737      * subj is expected to be in the format /type0=value0/type1=value1/type2=...
738      * where characters may be escaped by \
739      */
740     if (subj != NULL
741             && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
742         goto end;
743
744     if (!newreq) {
745         req = load_csr(infile, informat, "X509 request");
746         if (req == NULL)
747             goto end;
748     }
749
750     if (CAkeyfile == NULL)
751         CAkeyfile = CAfile;
752     if (CAkeyfile != NULL) {
753         if (CAfile == NULL) {
754             BIO_printf(bio_err,
755                        "Ignoring -CAkey option since no -CA option is given\n");
756         } else {
757             if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
758                                   0, passin, e,
759                                   CAkeyfile != CAfile
760                                   ? "issuer private key from -CAkey arg"
761                                   : "issuer private key from -CA arg")) == NULL)
762                 goto end;
763         }
764     }
765     if (CAfile != NULL) {
766         if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
767                                      "issuer cert from -CA arg")) == NULL)
768             goto end;
769         if (!X509_check_private_key(CAcert, CAkey)) {
770             BIO_printf(bio_err,
771                        "Issuer CA certificate and key do not match\n");
772             goto end;
773         }
774     }
775     if (newreq || gen_x509) {
776         if (pkey == NULL /* can happen only if !newreq */) {
777             BIO_printf(bio_err, "Must provide a signature key using -key\n");
778             goto end;
779         }
780
781         if (req == NULL) {
782             req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
783             if (req == NULL) {
784                 goto end;
785             }
786
787             if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){
788                 BIO_printf(bio_err, "Error making certificate request\n");
789                 goto end;
790             }
791         }
792         if (gen_x509) {
793             EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
794             EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey;
795             X509V3_CTX ext_ctx;
796             X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
797                 X509_REQ_get_subject_name(req);
798             X509_NAME *n_subj = fsubj != NULL ? fsubj :
799                 X509_REQ_get_subject_name(req);
800
801             if ((new_x509 = X509_new_ex(app_get0_libctx(),
802                                         app_get0_propq())) == NULL)
803                 goto end;
804
805             if (serial != NULL) {
806                 if (!X509_set_serialNumber(new_x509, serial))
807                     goto end;
808             } else {
809                 if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
810                     goto end;
811             }
812
813             if (!X509_set_issuer_name(new_x509, issuer))
814                 goto end;
815             if (days == UNSET_DAYS) {
816                 days = DEFAULT_DAYS;
817             }
818             if (!set_cert_times(new_x509, NULL, NULL, days))
819                 goto end;
820             if (!X509_set_subject_name(new_x509, n_subj))
821                 goto end;
822             if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
823                 goto end;
824             if (ext_copy == EXT_COPY_UNSET) {
825                 if (infile != NULL)
826                     BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
827             } else if (!copy_extensions(new_x509, req, ext_copy)) {
828                 BIO_printf(bio_err, "Error copying extensions from request\n");
829                 goto end;
830             }
831
832             /* Set up V3 context struct */
833             X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
834                            new_x509, NULL, NULL, X509V3_CTX_REPLACE);
835             /* prepare fallback for AKID, but only if issuer cert == new_x509 */
836             if (CAcert == NULL) {
837                 if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key))
838                     goto end;
839                 ERR_set_mark();
840                 if (!X509_check_private_key(new_x509, issuer_key))
841                     BIO_printf(bio_err,
842                                "Warning: Signature key and public key of cert do not match\n");
843                 ERR_pop_to_mark();
844             }
845             X509V3_set_nconf(&ext_ctx, req_conf);
846
847             /* Add extensions */
848             if (extensions != NULL
849                     && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions,
850                                              new_x509)) {
851                 BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
852                            extensions);
853                 goto end;
854             }
855             if (addext_conf != NULL
856                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
857                                          new_x509)) {
858                 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
859                 goto end;
860             }
861
862             /* If a pre-cert was requested, we need to add a poison extension */
863             if (precert) {
864                 if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
865                                       NULL, 1, 0) != 1) {
866                     BIO_printf(bio_err, "Error adding poison extension\n");
867                     goto end;
868                 }
869             }
870
871             i = do_X509_sign(new_x509, issuer_key, digest, sigopts, &ext_ctx);
872             if (!i)
873                 goto end;
874         } else {
875             X509V3_CTX ext_ctx;
876
877             /* Set up V3 context struct */
878             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
879             X509V3_set_nconf(&ext_ctx, req_conf);
880
881             /* Add extensions */
882             if (req_exts != NULL
883                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
884                                              req_exts, req)) {
885                 BIO_printf(bio_err, "Error adding request extensions from section %s\n",
886                            req_exts);
887                 goto end;
888             }
889             if (addext_conf != NULL
890                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
891                                              req)) {
892                 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
893                 goto end;
894             }
895             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
896             if (!i)
897                 goto end;
898         }
899     }
900
901     if (subj != NULL && !newreq && !gen_x509) {
902         if (verbose) {
903             BIO_printf(out, "Modifying subject of certificate request\n");
904             print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
905         }
906
907         if (!X509_REQ_set_subject_name(req, fsubj)) {
908             BIO_printf(bio_err, "Error modifying subject of certificate request\n");
909             goto end;
910         }
911
912         if (verbose) {
913             print_name(out, "New subject=", X509_REQ_get_subject_name(req));
914         }
915     }
916
917     if (verify) {
918         EVP_PKEY *tpubkey = pkey;
919
920         if (tpubkey == NULL) {
921             tpubkey = X509_REQ_get0_pubkey(req);
922             if (tpubkey == NULL)
923                 goto end;
924         }
925
926         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
927
928         if (i < 0)
929             goto end;
930         if (i == 0)
931             BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
932         else /* i > 0 */
933             BIO_printf(bio_err, "Certificate request self-signature verify OK\n");
934     }
935
936     if (noout && !text && !modulus && !subject && !pubkey) {
937         ret = 0;
938         goto end;
939     }
940
941     out = bio_open_default(outfile,
942                            keyout != NULL && outfile != NULL &&
943                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
944                            outformat);
945     if (out == NULL)
946         goto end;
947
948     if (pubkey) {
949         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
950
951         if (tpubkey == NULL) {
952             BIO_printf(bio_err, "Error getting public key\n");
953             goto end;
954         }
955         PEM_write_bio_PUBKEY(out, tpubkey);
956     }
957
958     if (text) {
959         if (gen_x509)
960             ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
961         else
962             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
963
964         if (ret == 0) {
965             if (gen_x509)
966                 BIO_printf(bio_err, "Error printing certificate\n");
967             else
968                 BIO_printf(bio_err, "Error printing certificate request\n");
969             goto end;
970         }
971     }
972
973     if (subject) {
974         print_name(out, "subject=", gen_x509
975                    ? X509_get_subject_name(new_x509)
976                    : X509_REQ_get_subject_name(req));
977     }
978
979     if (modulus) {
980         EVP_PKEY *tpubkey;
981
982         if (gen_x509)
983             tpubkey = X509_get0_pubkey(new_x509);
984         else
985             tpubkey = X509_REQ_get0_pubkey(req);
986         if (tpubkey == NULL) {
987             fprintf(stdout, "Modulus is unavailable\n");
988             goto end;
989         }
990         fprintf(stdout, "Modulus=");
991         if (EVP_PKEY_is_a(tpubkey, "RSA")) {
992             BIGNUM *n = NULL;
993
994             if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n))
995                 goto end;
996             BN_print(out, n);
997             BN_free(n);
998         } else {
999             fprintf(stdout, "Wrong Algorithm type");
1000         }
1001         fprintf(stdout, "\n");
1002     }
1003
1004     if (!noout && !gen_x509) {
1005         if (outformat == FORMAT_ASN1)
1006             i = i2d_X509_REQ_bio(out, req);
1007         else if (newhdr)
1008             i = PEM_write_bio_X509_REQ_NEW(out, req);
1009         else
1010             i = PEM_write_bio_X509_REQ(out, req);
1011         if (!i) {
1012             BIO_printf(bio_err, "Unable to write certificate request\n");
1013             goto end;
1014         }
1015     }
1016     if (!noout && gen_x509 && new_x509 != NULL) {
1017         if (outformat == FORMAT_ASN1)
1018             i = i2d_X509_bio(out, new_x509);
1019         else
1020             i = PEM_write_bio_X509(out, new_x509);
1021         if (!i) {
1022             BIO_printf(bio_err, "Unable to write X509 certificate\n");
1023             goto end;
1024         }
1025     }
1026     ret = 0;
1027  end:
1028     if (ret) {
1029         ERR_print_errors(bio_err);
1030     }
1031     NCONF_free(req_conf);
1032     NCONF_free(addext_conf);
1033     BIO_free(addext_bio);
1034     BIO_free_all(out);
1035     EVP_PKEY_free(pkey);
1036     EVP_PKEY_CTX_free(genctx);
1037     sk_OPENSSL_STRING_free(pkeyopts);
1038     sk_OPENSSL_STRING_free(sigopts);
1039     sk_OPENSSL_STRING_free(vfyopts);
1040     lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1041     lh_OPENSSL_STRING_free(addexts);
1042 #ifndef OPENSSL_NO_ENGINE
1043     release_engine(gen_eng);
1044 #endif
1045     OPENSSL_free(keyalgstr);
1046     X509_REQ_free(req);
1047     X509_NAME_free(fsubj);
1048     X509_free(new_x509);
1049     X509_free(CAcert);
1050     EVP_PKEY_free(CAkey);
1051     ASN1_INTEGER_free(serial);
1052     release_engine(e);
1053     if (passin != nofree_passin)
1054         OPENSSL_free(passin);
1055     if (passout != nofree_passout)
1056         OPENSSL_free(passout);
1057     return ret;
1058 }
1059
1060 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
1061                     int multirdn, int attribs, unsigned long chtype)
1062 {
1063     int ret = 0, i;
1064     char no_prompt = 0;
1065     STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
1066     char *tmp, *dn_sect, *attr_sect;
1067
1068     tmp = NCONF_get_string(req_conf, section, PROMPT);
1069     if (tmp == NULL)
1070         ERR_clear_error();
1071     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1072         no_prompt = 1;
1073
1074     dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1075     if (dn_sect == NULL) {
1076         ERR_clear_error();
1077     } else {
1078         dn_sk = NCONF_get_section(req_conf, dn_sect);
1079         if (dn_sk == NULL) {
1080             BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
1081             goto err;
1082         }
1083     }
1084
1085     attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1086     if (attr_sect == NULL) {
1087         ERR_clear_error();
1088     } else {
1089         attr_sk = NCONF_get_section(req_conf, attr_sect);
1090         if (attr_sk == NULL) {
1091             BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
1092             goto err;
1093         }
1094     }
1095
1096     /* so far there is only version 1 */
1097     if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
1098         goto err;
1099
1100     if (fsubj != NULL)
1101         i = X509_REQ_set_subject_name(req, fsubj);
1102     else if (no_prompt)
1103         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1104     else
1105         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1106                         chtype);
1107     if (!i)
1108         goto err;
1109
1110     if (!X509_REQ_set_pubkey(req, pkey))
1111         goto err;
1112
1113     ret = 1;
1114  err:
1115     return ret;
1116 }
1117
1118 static int prompt_info(X509_REQ *req,
1119                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1120                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1121                        int attribs, unsigned long chtype)
1122 {
1123     int i;
1124     char *p, *q;
1125     char buf[100];
1126     int nid, mval;
1127     long n_min, n_max;
1128     char *type, *value;
1129     const char *def;
1130     CONF_VALUE *v;
1131     X509_NAME *subj = X509_REQ_get_subject_name(req);
1132
1133     if (!batch) {
1134         BIO_printf(bio_err,
1135                    "You are about to be asked to enter information that will be incorporated\n");
1136         BIO_printf(bio_err, "into your certificate request.\n");
1137         BIO_printf(bio_err,
1138                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1139         BIO_printf(bio_err,
1140                    "There are quite a few fields but you can leave some blank\n");
1141         BIO_printf(bio_err,
1142                    "For some fields there will be a default value,\n");
1143         BIO_printf(bio_err,
1144                    "If you enter '.', the field will be left blank.\n");
1145         BIO_printf(bio_err, "-----\n");
1146     }
1147
1148     if (sk_CONF_VALUE_num(dn_sk)) {
1149         i = -1;
1150  start:
1151         for (;;) {
1152             i++;
1153             if (sk_CONF_VALUE_num(dn_sk) <= i)
1154                 break;
1155
1156             v = sk_CONF_VALUE_value(dn_sk, i);
1157             p = q = NULL;
1158             type = v->name;
1159             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1160                 !check_end(type, "_default") || !check_end(type, "_value"))
1161                 continue;
1162             /*
1163              * Skip past any leading X. X: X, etc to allow for multiple
1164              * instances
1165              */
1166             for (p = v->name; *p; p++)
1167                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1168                     p++;
1169                     if (*p)
1170                         type = p;
1171                     break;
1172                 }
1173             if (*type == '+') {
1174                 mval = -1;
1175                 type++;
1176             } else {
1177                 mval = 0;
1178             }
1179             /* If OBJ not recognised ignore it */
1180             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1181                 goto start;
1182             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1183                 return 0;
1184             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1185                 ERR_clear_error();
1186                 def = "";
1187             }
1188
1189             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1190                 return 0;
1191             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1192                 ERR_clear_error();
1193                 value = NULL;
1194             }
1195
1196             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1197                 return 0;
1198             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1199                 ERR_clear_error();
1200                 n_min = -1;
1201             }
1202
1203             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1204                 return 0;
1205             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1206                 ERR_clear_error();
1207                 n_max = -1;
1208             }
1209
1210             if (!add_DN_object(subj, v->value, def, value, nid,
1211                                n_min, n_max, chtype, mval))
1212                 return 0;
1213         }
1214         if (X509_NAME_entry_count(subj) == 0) {
1215             BIO_printf(bio_err, "Error: No objects specified in config file\n");
1216             return 0;
1217         }
1218
1219         if (attribs) {
1220             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1221                 && (!batch)) {
1222                 BIO_printf(bio_err,
1223                            "\nPlease enter the following 'extra' attributes\n");
1224                 BIO_printf(bio_err,
1225                            "to be sent with your certificate request\n");
1226             }
1227
1228             i = -1;
1229  start2:
1230             for (;;) {
1231                 i++;
1232                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1233                     break;
1234
1235                 v = sk_CONF_VALUE_value(attr_sk, i);
1236                 type = v->name;
1237                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1238                     goto start2;
1239
1240                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1241                     return 0;
1242                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1243                     == NULL) {
1244                     ERR_clear_error();
1245                     def = "";
1246                 }
1247
1248                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1249                     return 0;
1250                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1251                     == NULL) {
1252                     ERR_clear_error();
1253                     value = NULL;
1254                 }
1255
1256                 if (!join(buf, sizeof(buf), type, "_min", "Name"))
1257                     return 0;
1258                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1259                     ERR_clear_error();
1260                     n_min = -1;
1261                 }
1262
1263                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1264                     return 0;
1265                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1266                     ERR_clear_error();
1267                     n_max = -1;
1268                 }
1269
1270                 if (!add_attribute_object(req,
1271                                           v->value, def, value, nid, n_min,
1272                                           n_max, chtype))
1273                     return 0;
1274             }
1275         }
1276     } else {
1277         BIO_printf(bio_err, "No template, please set one up.\n");
1278         return 0;
1279     }
1280
1281     return 1;
1282
1283 }
1284
1285 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1286                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1287                      unsigned long chtype)
1288 {
1289     int i, spec_char, plus_char;
1290     char *p, *q;
1291     char *type;
1292     CONF_VALUE *v;
1293     X509_NAME *subj;
1294
1295     subj = X509_REQ_get_subject_name(req);
1296
1297     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1298         int mval;
1299         v = sk_CONF_VALUE_value(dn_sk, i);
1300         p = q = NULL;
1301         type = v->name;
1302         /*
1303          * Skip past any leading X. X: X, etc to allow for multiple instances
1304          */
1305         for (p = v->name; *p; p++) {
1306 #ifndef CHARSET_EBCDIC
1307             spec_char = (*p == ':' || *p == ',' || *p == '.');
1308 #else
1309             spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
1310                          || *p == os_toascii['.']);
1311 #endif
1312             if (spec_char) {
1313                 p++;
1314                 if (*p)
1315                     type = p;
1316                 break;
1317             }
1318         }
1319 #ifndef CHARSET_EBCDIC
1320         plus_char = (*type == '+');
1321 #else
1322         plus_char = (*type == os_toascii['+']);
1323 #endif
1324         if (plus_char) {
1325             type++;
1326             mval = -1;
1327         } else {
1328             mval = 0;
1329         }
1330         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1331                                         (unsigned char *)v->value, -1, -1,
1332                                         mval))
1333             return 0;
1334
1335     }
1336
1337     if (!X509_NAME_entry_count(subj)) {
1338         BIO_printf(bio_err, "Error: No objects specified in config file\n");
1339         return 0;
1340     }
1341     if (attribs) {
1342         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1343             v = sk_CONF_VALUE_value(attr_sk, i);
1344             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1345                                            (unsigned char *)v->value, -1))
1346                 return 0;
1347         }
1348     }
1349     return 1;
1350 }
1351
1352 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1353                          char *value, int nid, int n_min, int n_max,
1354                          unsigned long chtype, int mval)
1355 {
1356     int ret = 0;
1357     char buf[1024];
1358
1359     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1360                      "DN value", "DN default");
1361     if ((ret == 0) || (ret == 1))
1362         return ret;
1363     ret = 1;
1364
1365     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1366                                     (unsigned char *)buf, -1, -1, mval))
1367         ret = 0;
1368
1369     return ret;
1370 }
1371
1372 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1373                                 char *value, int nid, int n_min,
1374                                 int n_max, unsigned long chtype)
1375 {
1376     int ret = 0;
1377     char buf[1024];
1378
1379     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1380                      "Attribute value", "Attribute default");
1381     if ((ret == 0) || (ret == 1))
1382         return ret;
1383     ret = 1;
1384
1385     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1386                                    (unsigned char *)buf, -1)) {
1387         BIO_printf(bio_err, "Error adding attribute\n");
1388         ret = 0;
1389     }
1390
1391     return ret;
1392 }
1393
1394 static int build_data(char *text, const char *def, char *value,
1395                       int n_min, int n_max, char *buf, const int buf_size,
1396                       const char *desc1, const char *desc2)
1397 {
1398     int i;
1399  start:
1400     if (!batch)
1401         BIO_printf(bio_err, "%s [%s]:", text, def);
1402     (void)BIO_flush(bio_err);
1403     if (value != NULL) {
1404         if (!join(buf, buf_size, value, "\n", desc1))
1405             return 0;
1406         BIO_printf(bio_err, "%s\n", value);
1407     } else {
1408         buf[0] = '\0';
1409         if (!batch) {
1410             if (!fgets(buf, buf_size, stdin))
1411                 return 0;
1412         } else {
1413             buf[0] = '\n';
1414             buf[1] = '\0';
1415         }
1416     }
1417
1418     if (buf[0] == '\0')
1419         return 0;
1420     if (buf[0] == '\n') {
1421         if ((def == NULL) || (def[0] == '\0'))
1422             return 1;
1423         if (!join(buf, buf_size, def, "\n", desc2))
1424             return 0;
1425     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1426         return 1;
1427     }
1428
1429     i = strlen(buf);
1430     if (buf[i - 1] != '\n') {
1431         BIO_printf(bio_err, "Missing newline at end of input\n");
1432         return 0;
1433     }
1434     buf[--i] = '\0';
1435 #ifdef CHARSET_EBCDIC
1436     ebcdic2ascii(buf, buf, i);
1437 #endif
1438     if (!req_check_len(i, n_min, n_max)) {
1439         if (batch || value)
1440             return 0;
1441         goto start;
1442     }
1443     return 2;
1444 }
1445
1446 static int req_check_len(int len, int n_min, int n_max)
1447 {
1448     if (n_min > 0 && len < n_min) {
1449         BIO_printf(bio_err,
1450                    "String too short, must be at least %d bytes long\n", n_min);
1451         return 0;
1452     }
1453     if (n_max >= 0 && len > n_max) {
1454         BIO_printf(bio_err,
1455                    "String too long, must be at most %d bytes long\n", n_max);
1456         return 0;
1457     }
1458     return 1;
1459 }
1460
1461 /* Check if the end of a string matches 'end' */
1462 static int check_end(const char *str, const char *end)
1463 {
1464     size_t elen, slen;
1465     const char *tmp;
1466
1467     elen = strlen(end);
1468     slen = strlen(str);
1469     if (elen > slen)
1470         return 1;
1471     tmp = str + slen - elen;
1472     return strcmp(tmp, end);
1473 }
1474
1475 /*
1476  * Merge the two strings together into the result buffer checking for
1477  * overflow and producing an error message if there is.
1478  */
1479 static int join(char buf[], size_t buf_size, const char *name,
1480                 const char *tail, const char *desc)
1481 {
1482     const size_t name_len = strlen(name), tail_len = strlen(tail);
1483
1484     if (name_len + tail_len + 1 > buf_size) {
1485         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1486         return 0;
1487     }
1488     memcpy(buf, name, name_len);
1489     memcpy(buf + name_len, tail, tail_len + 1);
1490     return 1;
1491 }
1492
1493 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1494                                     char **pkeytype, long *pkeylen,
1495                                     ENGINE *keygen_engine)
1496 {
1497     EVP_PKEY_CTX *gctx = NULL;
1498     EVP_PKEY *param = NULL;
1499     long keylen = -1;
1500     BIO *pbio = NULL;
1501     const char *keytype = NULL;
1502     size_t keytypelen = 0;
1503     int expect_paramfile = 0;
1504     const char *paramfile = NULL;
1505
1506     /* Treat the first part of gstr, and only that */
1507     if (gstr == NULL) {
1508         /*
1509          * Special case: when no string given, default to RSA and the
1510          * key length given by |*pkeylen|.
1511          */
1512         keytype = "RSA";
1513         keylen = *pkeylen;
1514     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1515         /* Special case: only keylength given from string, so default to RSA */
1516         keytype = "RSA";
1517         /* The second part treatment will do the rest */
1518     } else {
1519         const char *p = strchr(gstr, ':');
1520         int len;
1521
1522         if (p != NULL)
1523             len = p - gstr;
1524         else
1525             len = strlen(gstr);
1526
1527         if (strncmp(gstr, "param", len) == 0) {
1528             expect_paramfile = 1;
1529             if (p == NULL) {
1530                 BIO_printf(bio_err,
1531                            "Parameter file requested but no path given: %s\n",
1532                            gstr);
1533                 return NULL;
1534             }
1535         } else {
1536             keytype = gstr;
1537             keytypelen = len;
1538         }
1539
1540         if (p != NULL)
1541             gstr = gstr + len + 1;
1542         else
1543             gstr = NULL;
1544     }
1545
1546     /* Treat the second part of gstr, if there is one */
1547     if (gstr != NULL) {
1548         /* If the second part starts with a digit, we assume it's a size */
1549         if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
1550             keylen = atol(gstr);
1551         else
1552             paramfile = gstr;
1553     }
1554
1555     if (paramfile != NULL) {
1556         pbio = BIO_new_file(paramfile, "r");
1557         if (pbio == NULL) {
1558             BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
1559             return NULL;
1560         }
1561         param = PEM_read_bio_Parameters(pbio, NULL);
1562
1563         if (param == NULL) {
1564             X509 *x;
1565
1566             (void)BIO_reset(pbio);
1567             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1568             if (x != NULL) {
1569                 param = X509_get_pubkey(x);
1570                 X509_free(x);
1571             }
1572         }
1573
1574         BIO_free(pbio);
1575
1576         if (param == NULL) {
1577             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1578             return NULL;
1579         }
1580         if (keytype == NULL) {
1581             keytype = EVP_PKEY_get0_type_name(param);
1582             if (keytype == NULL) {
1583                 EVP_PKEY_free(param);
1584                 BIO_puts(bio_err, "Unable to determine key type\n");
1585                 return NULL;
1586             }
1587         }
1588     }
1589
1590     if (keytypelen > 0)
1591         *pkeytype = OPENSSL_strndup(keytype, keytypelen);
1592     else
1593         *pkeytype = OPENSSL_strdup(keytype);
1594     if (keylen >= 0)
1595         *pkeylen = keylen;
1596
1597     if (param != NULL) {
1598         if (!EVP_PKEY_is_a(param, *pkeytype)) {
1599             BIO_printf(bio_err, "Key type does not match parameters\n");
1600             EVP_PKEY_free(param);
1601             return NULL;
1602         }
1603
1604         if (keygen_engine != NULL)
1605             gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1606         else
1607             gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
1608                                               param, app_get0_propq());
1609         *pkeylen = EVP_PKEY_get_bits(param);
1610         EVP_PKEY_free(param);
1611     } else {
1612         if (keygen_engine != NULL) {
1613             int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype,
1614                                              keygen_engine);
1615
1616             if (pkey_id != NID_undef)
1617                 gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
1618         } else {
1619             gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
1620                                               *pkeytype, app_get0_propq());
1621         }
1622     }
1623
1624     if (gctx == NULL) {
1625         BIO_puts(bio_err, "Error allocating keygen context\n");
1626         return NULL;
1627     }
1628
1629     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1630         BIO_puts(bio_err, "Error initializing keygen context\n");
1631         EVP_PKEY_CTX_free(gctx);
1632         return NULL;
1633     }
1634     if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
1635         || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
1636         keylen = *pkeylen;
1637
1638     if (keylen != -1) {
1639         OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
1640         size_t bits = keylen;
1641
1642         params[0] =
1643             OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
1644         if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
1645             BIO_puts(bio_err, "Error setting keysize\n");
1646             EVP_PKEY_CTX_free(gctx);
1647             return NULL;
1648         }
1649     }
1650
1651     return gctx;
1652 }
1653
1654 static 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     return 1;
1671 }