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