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