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