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