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