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