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