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