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