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