apps/req.c: Improve diagnostics on multiple/overriding X.509 extensions defined via...
[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 #ifndef OPENSSL_NO_RSA
29 # include <openssl/rsa.h>
30 #endif
31 #ifndef OPENSSL_NO_DSA
32 # include <openssl/dsa.h>
33 #endif
34
35 #define BITS            "default_bits"
36 #define KEYFILE         "default_keyfile"
37 #define PROMPT          "prompt"
38 #define DISTINGUISHED_NAME      "distinguished_name"
39 #define ATTRIBUTES      "attributes"
40 #define V3_EXTENSIONS   "x509_extensions"
41 #define REQ_EXTENSIONS  "req_extensions"
42 #define STRING_MASK     "string_mask"
43 #define UTF8_IN         "utf8"
44
45 #define DEFAULT_KEY_LENGTH      2048
46 #define MIN_KEY_LENGTH          512
47
48 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
49                     int attribs, unsigned long chtype);
50 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
51                          int multirdn);
52 static int prompt_info(X509_REQ *req,
53                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
54                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
55                        int attribs, unsigned long chtype);
56 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
57                      STACK_OF(CONF_VALUE) *attr, int attribs,
58                      unsigned long chtype);
59 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
60                                 char *value, int nid, int n_min, int n_max,
61                                 unsigned long chtype);
62 static int add_DN_object(X509_NAME *n, char *text, const char *def,
63                          char *value, int nid, int n_min, int n_max,
64                          unsigned long chtype, int mval);
65 static int genpkey_cb(EVP_PKEY_CTX *ctx);
66 static int build_data(char *text, const char *def,
67                       char *value, int n_min, int n_max,
68                       char *buf, const int buf_size,
69                       const char *desc1, const char *desc2
70                       );
71 static int req_check_len(int len, int n_min, int n_max);
72 static int check_end(const char *str, const char *end);
73 static int join(char buf[], size_t buf_size, const char *name,
74                 const char *tail, const char *desc);
75 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
76                                     int *pkey_type, long *pkeylen,
77                                     char **palgnam, ENGINE *keygen_engine);
78
79 static const char *section = "req";
80 static CONF *req_conf = NULL;
81 static CONF *addext_conf = NULL;
82 static int batch = 0;
83
84 typedef enum OPTION_choice {
85     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
86     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
87     OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
88     OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
89     OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
90     OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
91     OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
92     OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
93     OPT_REQEXTS, OPT_PRECERT, OPT_MD,
94     OPT_SECTION,
95     OPT_R_ENUM, OPT_PROV_ENUM
96 } OPTION_CHOICE;
97
98 const OPTIONS req_options[] = {
99     OPT_SECTION("General"),
100     {"help", OPT_HELP, '-', "Display this summary"},
101 #ifndef OPENSSL_NO_ENGINE
102     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
103     {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
104      "Specify engine to be used for key generation operations"},
105 #endif
106     {"in", OPT_IN, '<', "Input file"},
107     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
108     {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
109
110     OPT_SECTION("Certificate"),
111     {"new", OPT_NEW, '-', "New request"},
112     {"config", OPT_CONFIG, '<', "Request template file"},
113     {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
114     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
115     {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
116     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
117     {"text", OPT_TEXT, '-', "Text form of request"},
118     {"x509", OPT_X509, '-',
119      "Output an x509 structure instead of a cert request"},
120     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
121     {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
122     {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
123     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
124      "Deprecated; multi-valued RDNs support is always on."},
125     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
126     {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
127     {"addext", OPT_ADDEXT, 's',
128      "Additional cert extension key=value pair (may be given more than once)"},
129     {"extensions", OPT_EXTENSIONS, 's',
130      "Cert extension section (override value in config file)"},
131     {"reqexts", OPT_REQEXTS, 's',
132      "Request extension section (override value in config file)"},
133     {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
134
135     OPT_SECTION("Keys and Signing"),
136     {"key", OPT_KEY, 's', "Private key to use"},
137     {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
138     {"pubkey", OPT_PUBKEY, '-', "Output public key"},
139     {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
140     {"passin", OPT_PASSIN, 's', "Private key password source"},
141     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
142     {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
143     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
144     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
145     {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
146     {"", OPT_MD, '-', "Any supported digest"},
147
148     OPT_SECTION("Output"),
149     {"out", OPT_OUT, '>', "Output file"},
150     {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
151     {"batch", OPT_BATCH, '-',
152      "Do not ask anything during request generation"},
153     {"verbose", OPT_VERBOSE, '-', "Verbose output"},
154     {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
155     {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
156     {"noout", OPT_NOOUT, '-', "Do not output REQ"},
157     {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
158     {"modulus", OPT_MODULUS, '-', "RSA modulus"},
159
160     OPT_R_OPTIONS,
161     OPT_PROV_OPTIONS,
162     {NULL}
163 };
164
165
166 /*
167  * An LHASH of strings, where each string is an extension name.
168  */
169 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
170 {
171     return OPENSSL_LH_strhash((const char *)a);
172 }
173
174 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
175 {
176     return strcmp((const char *)a, (const char *)b);
177 }
178
179 static void exts_cleanup(OPENSSL_STRING *x)
180 {
181     OPENSSL_free((char *)x);
182 }
183
184 /*
185  * Is the |kv| key already duplicated?  This is remarkably tricky to get
186  * right.  Return 0 if unique, -1 on runtime error; 1 if found or a syntax
187  * error.
188  */
189 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
190 {
191     char *p;
192     size_t off;
193
194     /* Check syntax. */
195     /* Skip leading whitespace, make a copy. */
196     while (*kv && isspace(*kv))
197         if (*++kv == '\0')
198             return 1;
199     if ((p = strchr(kv, '=')) == NULL)
200         return 1;
201     off = p - kv;
202     if ((kv = OPENSSL_strdup(kv)) == NULL)
203         return -1;
204
205     /* Skip trailing space before the equal sign. */
206     for (p = kv + off; p > kv; --p)
207         if (!isspace(p[-1]))
208             break;
209     if (p == kv) {
210         OPENSSL_free(kv);
211         return 1;
212     }
213     *p = '\0';
214
215     /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
216     p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv);
217     if (p != NULL) {
218         OPENSSL_free(p);
219         return 1;
220     } else if (lh_OPENSSL_STRING_error(addexts)) {
221         OPENSSL_free(kv);
222         return -1;
223     }
224
225     return 0;
226 }
227
228 int req_main(int argc, char **argv)
229 {
230     ASN1_INTEGER *serial = NULL;
231     BIO *out = NULL;
232     ENGINE *e = NULL, *gen_eng = NULL;
233     EVP_PKEY *pkey = NULL;
234     EVP_PKEY_CTX *genctx = NULL;
235     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
236     LHASH_OF(OPENSSL_STRING) *addexts = NULL;
237     X509 *x509ss = NULL;
238     X509_REQ *req = NULL;
239     const EVP_CIPHER *cipher = NULL;
240     const EVP_MD *md_alg = NULL, *digest = NULL;
241     BIO *addext_bio = NULL;
242     char *extensions = NULL, *infile = NULL;
243     char *outfile = NULL, *keyfile = NULL;
244     char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
245     char *passin = NULL, *passout = NULL;
246     char *nofree_passin = NULL, *nofree_passout = NULL;
247     char *req_exts = NULL, *subj = NULL;
248     char *template = default_config_file, *keyout = NULL;
249     const char *keyalg = NULL;
250     OPTION_CHOICE o;
251     int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
252     int pkey_type = -1, private = 0;
253     int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
254     int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
255     int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
256     long newkey = -1;
257     unsigned long chtype = MBSTRING_ASC, reqflag = 0;
258
259 #ifndef OPENSSL_NO_DES
260     cipher = EVP_des_ede3_cbc();
261 #endif
262
263     prog = opt_init(argc, argv, req_options);
264     while ((o = opt_next()) != OPT_EOF) {
265         switch (o) {
266         case OPT_EOF:
267         case OPT_ERR:
268  opthelp:
269             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
270             goto end;
271         case OPT_HELP:
272             opt_help(req_options);
273             ret = 0;
274             goto end;
275         case OPT_INFORM:
276             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
277                 goto opthelp;
278             break;
279         case OPT_OUTFORM:
280             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
281                 goto opthelp;
282             break;
283         case OPT_ENGINE:
284             e = setup_engine(opt_arg(), 0);
285             break;
286         case OPT_KEYGEN_ENGINE:
287 #ifndef OPENSSL_NO_ENGINE
288             gen_eng = setup_engine(opt_arg(), 0);
289             if (gen_eng == NULL) {
290                 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
291                 goto opthelp;
292             }
293 #endif
294             break;
295         case OPT_KEY:
296             keyfile = opt_arg();
297             break;
298         case OPT_PUBKEY:
299             pubkey = 1;
300             break;
301         case OPT_NEW:
302             newreq = 1;
303             break;
304         case OPT_CONFIG:
305             template = opt_arg();
306             break;
307         case OPT_SECTION:
308             section = opt_arg();
309             break;
310         case OPT_KEYFORM:
311             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
312                 goto opthelp;
313             break;
314         case OPT_IN:
315             infile = opt_arg();
316             break;
317         case OPT_OUT:
318             outfile = opt_arg();
319             break;
320         case OPT_KEYOUT:
321             keyout = opt_arg();
322             break;
323         case OPT_PASSIN:
324             passargin = opt_arg();
325             break;
326         case OPT_PASSOUT:
327             passargout = opt_arg();
328             break;
329         case OPT_R_CASES:
330             if (!opt_rand(o))
331                 goto end;
332             break;
333         case OPT_PROV_CASES:
334             if (!opt_provider(o))
335                 goto end;
336             break;
337         case OPT_NEWKEY:
338             keyalg = opt_arg();
339             newreq = 1;
340             break;
341         case OPT_PKEYOPT:
342             if (pkeyopts == NULL)
343                 pkeyopts = sk_OPENSSL_STRING_new_null();
344             if (pkeyopts == NULL
345                     || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
346                 goto opthelp;
347             break;
348         case OPT_SIGOPT:
349             if (!sigopts)
350                 sigopts = sk_OPENSSL_STRING_new_null();
351             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
352                 goto opthelp;
353             break;
354         case OPT_VFYOPT:
355             if (!vfyopts)
356                 vfyopts = sk_OPENSSL_STRING_new_null();
357             if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
358                 goto opthelp;
359             break;
360         case OPT_BATCH:
361             batch = 1;
362             break;
363         case OPT_NEWHDR:
364             newhdr = 1;
365             break;
366         case OPT_MODULUS:
367             modulus = 1;
368             break;
369         case OPT_VERIFY:
370             verify = 1;
371             break;
372         case OPT_NODES:
373         case OPT_NOENC:
374             noenc = 1;
375             break;
376         case OPT_NOOUT:
377             noout = 1;
378             break;
379         case OPT_VERBOSE:
380             verbose = 1;
381             break;
382         case OPT_UTF8:
383             chtype = MBSTRING_UTF8;
384             break;
385         case OPT_NAMEOPT:
386             if (!set_nameopt(opt_arg()))
387                 goto opthelp;
388             break;
389         case OPT_REQOPT:
390             if (!set_cert_ex(&reqflag, opt_arg()))
391                 goto opthelp;
392             break;
393         case OPT_TEXT:
394             text = 1;
395             break;
396         case OPT_X509:
397             x509 = 1;
398             break;
399         case OPT_DAYS:
400             days = atoi(opt_arg());
401             break;
402         case OPT_SET_SERIAL:
403             if (serial != NULL) {
404                 BIO_printf(bio_err, "Serial number supplied twice\n");
405                 goto opthelp;
406             }
407             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
408             if (serial == NULL)
409                 goto opthelp;
410             break;
411         case OPT_SUBJECT:
412             subject = 1;
413             break;
414         case OPT_SUBJ:
415             subj = opt_arg();
416             break;
417         case OPT_MULTIVALUE_RDN:
418             /* obsolete */
419             break;
420         case OPT_ADDEXT:
421             p = opt_arg();
422             if (addexts == NULL) {
423                 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
424                 addext_bio = BIO_new(BIO_s_mem());
425                 if (addexts == NULL || addext_bio == NULL)
426                     goto end;
427             }
428             i = duplicated(addexts, p);
429             if (i == 1) {
430                 BIO_printf(bio_err, "Duplicate extension: %s\n", p);
431                 goto opthelp;
432             }
433             if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
434                 goto end;
435             break;
436         case OPT_EXTENSIONS:
437             extensions = opt_arg();
438             break;
439         case OPT_REQEXTS:
440             req_exts = opt_arg();
441             break;
442         case OPT_PRECERT:
443             newreq = precert = 1;
444             break;
445         case OPT_MD:
446             if (!opt_md(opt_unknown(), &md_alg))
447                 goto opthelp;
448             digest = md_alg;
449             break;
450         }
451     }
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 loading 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 loading 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 loading 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 ((extensions != NULL || addext_conf != NULL)
748                 && !X509_set_version(x509ss, 2))
749                 goto end;
750             if (serial != NULL) {
751                 if (!X509_set_serialNumber(x509ss, serial))
752                     goto end;
753             } else {
754                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
755                     goto end;
756             }
757
758             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
759                 goto end;
760             if (days == 0) {
761                 /* set default days if it's not specified */
762                 days = 30;
763             }
764             if (!set_cert_times(x509ss, NULL, NULL, days))
765                 goto end;
766             if (!X509_set_subject_name
767                 (x509ss, X509_REQ_get_subject_name(req)))
768                 goto end;
769             tmppkey = X509_REQ_get0_pubkey(req);
770             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
771                 goto end;
772
773             /* Set up V3 context struct */
774
775             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
776             X509V3_set_nconf(&ext_ctx, req_conf);
777
778             /* Add extensions */
779             if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
780                                                             &ext_ctx, extensions,
781                                                             x509ss)) {
782                 BIO_printf(bio_err, "Error loading extension section %s\n",
783                            extensions);
784                 goto end;
785             }
786             if (addext_conf != NULL
787                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
788                                          x509ss)) {
789                 BIO_printf(bio_err, "Error loading extensions defined via -addext\n");
790                 goto end;
791             }
792
793             /* If a pre-cert was requested, we need to add a poison extension */
794             if (precert) {
795                 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
796                     != 1) {
797                     BIO_printf(bio_err, "Error adding poison extension\n");
798                     goto end;
799                 }
800             }
801
802             i = do_X509_sign(x509ss, pkey, digest, sigopts);
803             if (!i) {
804                 ERR_print_errors(bio_err);
805                 goto end;
806             }
807         } else {
808             X509V3_CTX ext_ctx;
809
810             /* Set up V3 context struct */
811
812             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
813             X509V3_set_nconf(&ext_ctx, req_conf);
814
815             /* Add extensions */
816             if (req_exts != NULL
817                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
818                                              req_exts, req)) {
819                 BIO_printf(bio_err, "Error loading extension section %s\n",
820                            req_exts);
821                 goto end;
822             }
823             if (addext_conf != NULL
824                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
825                                              req)) {
826                 BIO_printf(bio_err, "Error loading extensions defined via -addext\n");
827                 goto end;
828             }
829             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
830             if (!i) {
831                 ERR_print_errors(bio_err);
832                 goto end;
833             }
834         }
835     }
836
837     if (subj && x509) {
838         BIO_printf(bio_err, "Cannot modify certificate subject\n");
839         goto end;
840     }
841
842     if (subj && !x509) {
843         if (verbose) {
844             BIO_printf(bio_err, "Modifying Request's Subject\n");
845             print_name(bio_err, "old subject=",
846                        X509_REQ_get_subject_name(req), get_nameopt());
847         }
848
849         if (build_subject(req, subj, chtype, multirdn) == 0) {
850             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
851             ret = 1;
852             goto end;
853         }
854
855         if (verbose) {
856             print_name(bio_err, "new subject=",
857                        X509_REQ_get_subject_name(req), get_nameopt());
858         }
859     }
860
861     if (verify && !x509) {
862         EVP_PKEY *tpubkey = pkey;
863
864         if (tpubkey == NULL) {
865             tpubkey = X509_REQ_get0_pubkey(req);
866             if (tpubkey == NULL)
867                 goto end;
868         }
869
870         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
871
872         if (i < 0) {
873             goto end;
874         } else if (i == 0) {
875             BIO_printf(bio_err, "verify failure\n");
876             ERR_print_errors(bio_err);
877         } else {                 /* if (i > 0) */
878             BIO_printf(bio_err, "verify OK\n");
879         }
880     }
881
882     if (noout && !text && !modulus && !subject && !pubkey) {
883         ret = 0;
884         goto end;
885     }
886
887     out = bio_open_default(outfile,
888                            keyout != NULL && outfile != NULL &&
889                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
890                            outformat);
891     if (out == NULL)
892         goto end;
893
894     if (pubkey) {
895         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
896
897         if (tpubkey == NULL) {
898             BIO_printf(bio_err, "Error getting public key\n");
899             ERR_print_errors(bio_err);
900             goto end;
901         }
902         PEM_write_bio_PUBKEY(out, tpubkey);
903     }
904
905     if (text) {
906         if (x509)
907             ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
908         else
909             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
910
911         if (ret == 0) {
912             if (x509)
913               BIO_printf(bio_err, "Error printing certificate\n");
914             else
915               BIO_printf(bio_err, "Error printing certificate request\n");
916
917             ERR_print_errors(bio_err);
918             goto end;
919         }
920     }
921
922     if (subject) {
923         if (x509)
924             print_name(out, "subject=", X509_get_subject_name(x509ss),
925                        get_nameopt());
926         else
927             print_name(out, "subject=", X509_REQ_get_subject_name(req),
928                        get_nameopt());
929     }
930
931     if (modulus) {
932         EVP_PKEY *tpubkey;
933
934         if (x509)
935             tpubkey = X509_get0_pubkey(x509ss);
936         else
937             tpubkey = X509_REQ_get0_pubkey(req);
938         if (tpubkey == NULL) {
939             fprintf(stdout, "Modulus=unavailable\n");
940             goto end;
941         }
942         fprintf(stdout, "Modulus=");
943 #ifndef OPENSSL_NO_RSA
944         if (EVP_PKEY_is_a(tpubkey, "RSA")) {
945             BIGNUM *n;
946
947             /* Every RSA key has an 'n' */
948             EVP_PKEY_get_bn_param(pkey, "n", &n);
949             BN_print(out, n);
950             BN_free(n);
951         } else
952 #endif
953             fprintf(stdout, "Wrong Algorithm type");
954         fprintf(stdout, "\n");
955     }
956
957     if (!noout && !x509) {
958         if (outformat == FORMAT_ASN1)
959             i = i2d_X509_REQ_bio(out, req);
960         else if (newhdr)
961             i = PEM_write_bio_X509_REQ_NEW(out, req);
962         else
963             i = PEM_write_bio_X509_REQ(out, req);
964         if (!i) {
965             BIO_printf(bio_err, "unable to write X509 request\n");
966             goto end;
967         }
968     }
969     if (!noout && x509 && (x509ss != NULL)) {
970         if (outformat == FORMAT_ASN1)
971             i = i2d_X509_bio(out, x509ss);
972         else
973             i = PEM_write_bio_X509(out, x509ss);
974         if (!i) {
975             BIO_printf(bio_err, "unable to write X509 certificate\n");
976             goto end;
977         }
978     }
979     ret = 0;
980  end:
981     if (ret) {
982         ERR_print_errors(bio_err);
983     }
984     NCONF_free(req_conf);
985     NCONF_free(addext_conf);
986     BIO_free(addext_bio);
987     BIO_free_all(out);
988     EVP_PKEY_free(pkey);
989     EVP_PKEY_CTX_free(genctx);
990     sk_OPENSSL_STRING_free(pkeyopts);
991     sk_OPENSSL_STRING_free(sigopts);
992     sk_OPENSSL_STRING_free(vfyopts);
993     lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
994     lh_OPENSSL_STRING_free(addexts);
995 #ifndef OPENSSL_NO_ENGINE
996     release_engine(gen_eng);
997 #endif
998     OPENSSL_free(keyalgstr);
999     X509_REQ_free(req);
1000     X509_free(x509ss);
1001     ASN1_INTEGER_free(serial);
1002     release_engine(e);
1003     if (passin != nofree_passin)
1004         OPENSSL_free(passin);
1005     if (passout != nofree_passout)
1006         OPENSSL_free(passout);
1007     return ret;
1008 }
1009
1010 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1011                     int attribs, unsigned long chtype)
1012 {
1013     int ret = 0, i;
1014     char no_prompt = 0;
1015     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1016     char *tmp, *dn_sect, *attr_sect;
1017
1018     tmp = NCONF_get_string(req_conf, section, PROMPT);
1019     if (tmp == NULL)
1020         ERR_clear_error();
1021     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1022         no_prompt = 1;
1023
1024     dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1025     if (dn_sect == NULL) {
1026         BIO_printf(bio_err, "unable to find '%s' in config\n",
1027                    DISTINGUISHED_NAME);
1028         goto err;
1029     }
1030     dn_sk = NCONF_get_section(req_conf, dn_sect);
1031     if (dn_sk == NULL) {
1032         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1033         goto err;
1034     }
1035
1036     attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1037     if (attr_sect == NULL) {
1038         ERR_clear_error();
1039         attr_sk = NULL;
1040     } else {
1041         attr_sk = NCONF_get_section(req_conf, attr_sect);
1042         if (attr_sk == NULL) {
1043             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1044             goto err;
1045         }
1046     }
1047
1048     /* setup version number */
1049     if (!X509_REQ_set_version(req, 0L))
1050         goto err;               /* version 1 */
1051
1052     if (subj)
1053         i = build_subject(req, subj, chtype, multirdn);
1054     else if (no_prompt)
1055         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1056     else
1057         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1058                         chtype);
1059     if (!i)
1060         goto err;
1061
1062     if (!X509_REQ_set_pubkey(req, pkey))
1063         goto err;
1064
1065     ret = 1;
1066  err:
1067     return ret;
1068 }
1069
1070 /*
1071  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1072  * where characters may be escaped by \
1073  */
1074 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1075                          int multirdn)
1076 {
1077     X509_NAME *n;
1078
1079     if ((n = parse_name(subject, chtype, multirdn, "subject")) == NULL)
1080         return 0;
1081
1082     if (!X509_REQ_set_subject_name(req, n)) {
1083         X509_NAME_free(n);
1084         return 0;
1085     }
1086     X509_NAME_free(n);
1087     return 1;
1088 }
1089
1090 static int prompt_info(X509_REQ *req,
1091                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1092                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1093                        int attribs, unsigned long chtype)
1094 {
1095     int i;
1096     char *p, *q;
1097     char buf[100];
1098     int nid, mval;
1099     long n_min, n_max;
1100     char *type, *value;
1101     const char *def;
1102     CONF_VALUE *v;
1103     X509_NAME *subj = X509_REQ_get_subject_name(req);
1104
1105     if (!batch) {
1106         BIO_printf(bio_err,
1107                    "You are about to be asked to enter information that will be incorporated\n");
1108         BIO_printf(bio_err, "into your certificate request.\n");
1109         BIO_printf(bio_err,
1110                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1111         BIO_printf(bio_err,
1112                    "There are quite a few fields but you can leave some blank\n");
1113         BIO_printf(bio_err,
1114                    "For some fields there will be a default value,\n");
1115         BIO_printf(bio_err,
1116                    "If you enter '.', the field will be left blank.\n");
1117         BIO_printf(bio_err, "-----\n");
1118     }
1119
1120     if (sk_CONF_VALUE_num(dn_sk)) {
1121         i = -1;
1122  start:
1123         for ( ; ; ) {
1124             i++;
1125             if (sk_CONF_VALUE_num(dn_sk) <= i)
1126                 break;
1127
1128             v = sk_CONF_VALUE_value(dn_sk, i);
1129             p = q = NULL;
1130             type = v->name;
1131             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1132                 !check_end(type, "_default") || !check_end(type, "_value"))
1133                 continue;
1134             /*
1135              * Skip past any leading X. X: X, etc to allow for multiple
1136              * instances
1137              */
1138             for (p = v->name; *p; p++)
1139                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1140                     p++;
1141                     if (*p)
1142                         type = p;
1143                     break;
1144                 }
1145             if (*type == '+') {
1146                 mval = -1;
1147                 type++;
1148             } else {
1149                 mval = 0;
1150             }
1151             /* If OBJ not recognised ignore it */
1152             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1153                 goto start;
1154             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1155                 return 0;
1156             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1157                 ERR_clear_error();
1158                 def = "";
1159             }
1160
1161             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1162                 return 0;
1163             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1164                 ERR_clear_error();
1165                 value = NULL;
1166             }
1167
1168             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1169                 return 0;
1170             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1171                 ERR_clear_error();
1172                 n_min = -1;
1173             }
1174
1175
1176             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1177                 return 0;
1178             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1179                 ERR_clear_error();
1180                 n_max = -1;
1181             }
1182
1183             if (!add_DN_object(subj, v->value, def, value, nid,
1184                                n_min, n_max, chtype, mval))
1185                 return 0;
1186         }
1187         if (X509_NAME_entry_count(subj) == 0) {
1188             BIO_printf(bio_err, "error, no objects specified in config file\n");
1189             return 0;
1190         }
1191
1192         if (attribs) {
1193             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1194                 && (!batch)) {
1195                 BIO_printf(bio_err,
1196                            "\nPlease enter the following 'extra' attributes\n");
1197                 BIO_printf(bio_err,
1198                            "to be sent with your certificate request\n");
1199             }
1200
1201             i = -1;
1202  start2:
1203             for ( ; ; ) {
1204                 i++;
1205                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1206                     break;
1207
1208                 v = sk_CONF_VALUE_value(attr_sk, i);
1209                 type = v->name;
1210                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1211                     goto start2;
1212
1213                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1214                     return 0;
1215                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1216                     == NULL) {
1217                     ERR_clear_error();
1218                     def = "";
1219                 }
1220
1221                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1222                     return 0;
1223                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1224                     == NULL) {
1225                     ERR_clear_error();
1226                     value = NULL;
1227                 }
1228
1229                 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1230                     return 0;
1231                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1232                     ERR_clear_error();
1233                     n_min = -1;
1234                 }
1235
1236                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1237                     return 0;
1238                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1239                     ERR_clear_error();
1240                     n_max = -1;
1241                 }
1242
1243                 if (!add_attribute_object(req,
1244                                           v->value, def, value, nid, n_min,
1245                                           n_max, chtype))
1246                     return 0;
1247             }
1248         }
1249     } else {
1250         BIO_printf(bio_err, "No template, please set one up.\n");
1251         return 0;
1252     }
1253
1254     return 1;
1255
1256 }
1257
1258 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1259                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1260                      unsigned long chtype)
1261 {
1262     int i, spec_char, plus_char;
1263     char *p, *q;
1264     char *type;
1265     CONF_VALUE *v;
1266     X509_NAME *subj;
1267
1268     subj = X509_REQ_get_subject_name(req);
1269
1270     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1271         int mval;
1272         v = sk_CONF_VALUE_value(dn_sk, i);
1273         p = q = NULL;
1274         type = v->name;
1275         /*
1276          * Skip past any leading X. X: X, etc to allow for multiple instances
1277          */
1278         for (p = v->name; *p; p++) {
1279 #ifndef CHARSET_EBCDIC
1280             spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1281 #else
1282             spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1283                     || (*p == os_toascii['.']));
1284 #endif
1285             if (spec_char) {
1286                 p++;
1287                 if (*p)
1288                     type = p;
1289                 break;
1290             }
1291         }
1292 #ifndef CHARSET_EBCDIC
1293         plus_char = (*type == '+');
1294 #else
1295         plus_char = (*type == os_toascii['+']);
1296 #endif
1297         if (plus_char) {
1298             type++;
1299             mval = -1;
1300         } else {
1301             mval = 0;
1302         }
1303         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1304                                         (unsigned char *)v->value, -1, -1,
1305                                         mval))
1306             return 0;
1307
1308     }
1309
1310     if (!X509_NAME_entry_count(subj)) {
1311         BIO_printf(bio_err, "error, no objects specified in config file\n");
1312         return 0;
1313     }
1314     if (attribs) {
1315         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1316             v = sk_CONF_VALUE_value(attr_sk, i);
1317             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1318                                            (unsigned char *)v->value, -1))
1319                 return 0;
1320         }
1321     }
1322     return 1;
1323 }
1324
1325 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1326                          char *value, int nid, int n_min, int n_max,
1327                          unsigned long chtype, int mval)
1328 {
1329     int ret = 0;
1330     char buf[1024];
1331
1332     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1333                      "DN value", "DN default");
1334     if ((ret == 0) || (ret == 1))
1335         return ret;
1336     ret = 1;
1337
1338     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1339                                     (unsigned char *)buf, -1, -1, mval))
1340         ret = 0;
1341
1342     return ret;
1343 }
1344
1345 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1346                                 char *value, int nid, int n_min,
1347                                 int n_max, unsigned long chtype)
1348 {
1349     int ret = 0;
1350     char buf[1024];
1351
1352     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1353                      "Attribute value", "Attribute default");
1354     if ((ret == 0) || (ret == 1))
1355         return ret;
1356     ret = 1;
1357
1358     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1359                                    (unsigned char *)buf, -1)) {
1360         BIO_printf(bio_err, "Error adding attribute\n");
1361         ERR_print_errors(bio_err);
1362         ret = 0;
1363     }
1364
1365     return ret;
1366 }
1367
1368
1369 static int build_data(char *text, const char *def,
1370                          char *value, int n_min, int n_max,
1371                          char *buf, const int buf_size,
1372                          const char *desc1, const char *desc2
1373                          )
1374 {
1375     int i;
1376  start:
1377     if (!batch)
1378         BIO_printf(bio_err, "%s [%s]:", text, def);
1379     (void)BIO_flush(bio_err);
1380     if (value != NULL) {
1381         if (!join(buf, buf_size, value, "\n", desc1))
1382             return 0;
1383         BIO_printf(bio_err, "%s\n", value);
1384     } else {
1385         buf[0] = '\0';
1386         if (!batch) {
1387             if (!fgets(buf, buf_size, stdin))
1388                 return 0;
1389         } else {
1390             buf[0] = '\n';
1391             buf[1] = '\0';
1392         }
1393     }
1394
1395     if (buf[0] == '\0')
1396         return 0;
1397     if (buf[0] == '\n') {
1398         if ((def == NULL) || (def[0] == '\0'))
1399             return 1;
1400         if (!join(buf, buf_size, def, "\n", desc2))
1401             return 0;
1402     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1403         return 1;
1404     }
1405
1406     i = strlen(buf);
1407     if (buf[i - 1] != '\n') {
1408         BIO_printf(bio_err, "weird input :-(\n");
1409         return 0;
1410     }
1411     buf[--i] = '\0';
1412 #ifdef CHARSET_EBCDIC
1413     ebcdic2ascii(buf, buf, i);
1414 #endif
1415     if (!req_check_len(i, n_min, n_max)) {
1416         if (batch || value)
1417             return 0;
1418         goto start;
1419     }
1420     return 2;
1421 }
1422
1423 static int req_check_len(int len, int n_min, int n_max)
1424 {
1425     if ((n_min > 0) && (len < n_min)) {
1426         BIO_printf(bio_err,
1427                    "string is too short, it needs to be at least %d bytes long\n",
1428                    n_min);
1429         return 0;
1430     }
1431     if ((n_max >= 0) && (len > n_max)) {
1432         BIO_printf(bio_err,
1433                    "string is too long, it needs to be no more than %d bytes long\n",
1434                    n_max);
1435         return 0;
1436     }
1437     return 1;
1438 }
1439
1440 /* Check if the end of a string matches 'end' */
1441 static int check_end(const char *str, const char *end)
1442 {
1443     size_t elen, slen;
1444     const char *tmp;
1445
1446     elen = strlen(end);
1447     slen = strlen(str);
1448     if (elen > slen)
1449         return 1;
1450     tmp = str + slen - elen;
1451     return strcmp(tmp, end);
1452 }
1453
1454 /*
1455  * Merge the two strings together into the result buffer checking for
1456  * overflow and producing an error message if there is.
1457  */
1458 static int join(char buf[], size_t buf_size, const char *name,
1459                 const char *tail, const char *desc)
1460 {
1461     const size_t name_len = strlen(name), tail_len = strlen(tail);
1462
1463     if (name_len + tail_len + 1 > buf_size) {
1464         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1465         return 0;
1466     }
1467     memcpy(buf, name, name_len);
1468     memcpy(buf + name_len, tail, tail_len + 1);
1469     return 1;
1470 }
1471
1472 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1473                                     int *pkey_type, long *pkeylen,
1474                                     char **palgnam, ENGINE *keygen_engine)
1475 {
1476     EVP_PKEY_CTX *gctx = NULL;
1477     EVP_PKEY *param = NULL;
1478     long keylen = -1;
1479     BIO *pbio = NULL;
1480     const char *paramfile = NULL;
1481
1482     if (gstr == NULL) {
1483         *pkey_type = EVP_PKEY_RSA;
1484         keylen = *pkeylen;
1485     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1486         *pkey_type = EVP_PKEY_RSA;
1487         keylen = atol(gstr);
1488         *pkeylen = keylen;
1489     } else if (strncmp(gstr, "param:", 6) == 0) {
1490         paramfile = gstr + 6;
1491     } else {
1492         const char *p = strchr(gstr, ':');
1493         int len;
1494         ENGINE *tmpeng;
1495         const EVP_PKEY_ASN1_METHOD *ameth;
1496
1497         if (p != NULL)
1498             len = p - gstr;
1499         else
1500             len = strlen(gstr);
1501         /*
1502          * The lookup of a the string will cover all engines so keep a note
1503          * of the implementation.
1504          */
1505
1506         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1507
1508         if (ameth == NULL) {
1509             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1510             return NULL;
1511         }
1512
1513         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1514 #ifndef OPENSSL_NO_ENGINE
1515         finish_engine(tmpeng);
1516 #endif
1517         if (*pkey_type == EVP_PKEY_RSA) {
1518             if (p != NULL) {
1519                 keylen = atol(p + 1);
1520                 *pkeylen = keylen;
1521             } else {
1522                 keylen = *pkeylen;
1523             }
1524         } else if (p != NULL) {
1525             paramfile = p + 1;
1526         }
1527     }
1528
1529     if (paramfile != NULL) {
1530         pbio = BIO_new_file(paramfile, "r");
1531         if (pbio == NULL) {
1532             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1533             return NULL;
1534         }
1535         param = PEM_read_bio_Parameters(pbio, NULL);
1536
1537         if (param == NULL) {
1538             X509 *x;
1539
1540             (void)BIO_reset(pbio);
1541             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1542             if (x != NULL) {
1543                 param = X509_get_pubkey(x);
1544                 X509_free(x);
1545             }
1546         }
1547
1548         BIO_free(pbio);
1549
1550         if (param == NULL) {
1551             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1552             return NULL;
1553         }
1554         if (*pkey_type == -1) {
1555             *pkey_type = EVP_PKEY_id(param);
1556         } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1557             BIO_printf(bio_err, "Key Type does not match parameters\n");
1558             EVP_PKEY_free(param);
1559             return NULL;
1560         }
1561     }
1562
1563     if (palgnam != NULL) {
1564         const EVP_PKEY_ASN1_METHOD *ameth;
1565         ENGINE *tmpeng;
1566         const char *anam;
1567
1568         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1569         if (ameth == NULL) {
1570             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1571             return NULL;
1572         }
1573         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1574         *palgnam = OPENSSL_strdup(anam);
1575 #ifndef OPENSSL_NO_ENGINE
1576         finish_engine(tmpeng);
1577 #endif
1578     }
1579
1580     if (param != NULL) {
1581         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1582         *pkeylen = EVP_PKEY_bits(param);
1583         EVP_PKEY_free(param);
1584     } else {
1585         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1586     }
1587
1588     if (gctx == NULL) {
1589         BIO_puts(bio_err, "Error allocating keygen context\n");
1590         ERR_print_errors(bio_err);
1591         return NULL;
1592     }
1593
1594     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1595         BIO_puts(bio_err, "Error initializing keygen context\n");
1596         ERR_print_errors(bio_err);
1597         EVP_PKEY_CTX_free(gctx);
1598         return NULL;
1599     }
1600 #ifndef OPENSSL_NO_RSA
1601     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1602         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1603             BIO_puts(bio_err, "Error setting RSA keysize\n");
1604             ERR_print_errors(bio_err);
1605             EVP_PKEY_CTX_free(gctx);
1606             return NULL;
1607         }
1608     }
1609 #endif
1610
1611     return gctx;
1612 }
1613
1614 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1615 {
1616     char c = '*';
1617     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1618     int p;
1619     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1620     if (p == 0)
1621         c = '.';
1622     if (p == 1)
1623         c = '+';
1624     if (p == 2)
1625         c = '*';
1626     if (p == 3)
1627         c = '\n';
1628     BIO_write(b, &c, 1);
1629     (void)BIO_flush(b);
1630     return 1;
1631 }
1632
1633 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1634 {
1635     int i;
1636
1637     if (opts == NULL)
1638         return 1;
1639
1640     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1641         char *opt = sk_OPENSSL_STRING_value(opts, i);
1642         if (pkey_ctrl_string(pkctx, opt) <= 0) {
1643             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1644             ERR_print_errors(bio_err);
1645             return 0;
1646         }
1647     }
1648
1649     return 1;
1650 }
1651
1652 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1653 {
1654     int i;
1655
1656     if (opts == NULL)
1657         return 1;
1658
1659     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1660         char *opt = sk_OPENSSL_STRING_value(opts, i);
1661         if (x509_ctrl_string(x, opt) <= 0) {
1662             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1663             ERR_print_errors(bio_err);
1664             return 0;
1665         }
1666     }
1667
1668     return 1;
1669 }
1670
1671 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1672 {
1673     int i;
1674
1675     if (opts == NULL)
1676         return 1;
1677
1678     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1679         char *opt = sk_OPENSSL_STRING_value(opts, i);
1680         if (x509_req_ctrl_string(x, opt) <= 0) {
1681             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1682             ERR_print_errors(bio_err);
1683             return 0;
1684         }
1685     }
1686
1687     return 1;
1688 }
1689
1690 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1691                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1692 {
1693     EVP_PKEY_CTX *pkctx = NULL;
1694     int def_nid;
1695
1696     if (ctx == NULL)
1697         return 0;
1698     /*
1699      * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1700      * for this algorithm.
1701      */
1702     if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1703             && def_nid == NID_undef) {
1704         /* The signing algorithm requires there to be no digest */
1705         md = NULL;
1706     }
1707     return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1708         && do_pkey_ctx_init(pkctx, sigopts);
1709 }
1710
1711 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1712                  STACK_OF(OPENSSL_STRING) *sigopts)
1713 {
1714     int rv = 0;
1715     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1716
1717     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1718         rv = (X509_sign_ctx(x, mctx) > 0);
1719     EVP_MD_CTX_free(mctx);
1720     return rv;
1721 }
1722
1723 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1724                      STACK_OF(OPENSSL_STRING) *sigopts)
1725 {
1726     int rv = 0;
1727     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1728
1729     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1730         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1731     EVP_MD_CTX_free(mctx);
1732     return rv;
1733 }
1734
1735 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1736 {
1737     int rv = 0;
1738
1739     if (do_x509_init(x, vfyopts) > 0)
1740         rv = (X509_verify(x, pkey) > 0);
1741     return rv;
1742 }
1743
1744 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1745                        STACK_OF(OPENSSL_STRING) *vfyopts)
1746 {
1747     int rv = 0;
1748
1749     if (do_x509_req_init(x, vfyopts) > 0)
1750         rv = (X509_REQ_verify(x, pkey) > 0);
1751     return rv;
1752 }
1753
1754 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1755                      STACK_OF(OPENSSL_STRING) *sigopts)
1756 {
1757     int rv = 0;
1758     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1759
1760     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1761         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1762     EVP_MD_CTX_free(mctx);
1763     return rv;
1764 }