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