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