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