Correct error output of parse_name() in apps/lib/apps.c and apps/cmp.c
[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_STACK_OF(CONF_VALUE)
36 DEFINE_STACK_OF_STRING()
37
38 #define BITS            "default_bits"
39 #define KEYFILE         "default_keyfile"
40 #define PROMPT          "prompt"
41 #define DISTINGUISHED_NAME      "distinguished_name"
42 #define ATTRIBUTES      "attributes"
43 #define V3_EXTENSIONS   "x509_extensions"
44 #define REQ_EXTENSIONS  "req_extensions"
45 #define STRING_MASK     "string_mask"
46 #define UTF8_IN         "utf8"
47
48 #define DEFAULT_KEY_LENGTH      2048
49 #define MIN_KEY_LENGTH          512
50
51 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
52                     int attribs, unsigned long chtype);
53 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
54                          int multirdn);
55 static int prompt_info(X509_REQ *req,
56                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
57                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
58                        int attribs, unsigned long chtype);
59 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
60                      STACK_OF(CONF_VALUE) *attr, int attribs,
61                      unsigned long chtype);
62 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
63                                 char *value, int nid, int n_min, int n_max,
64                                 unsigned long chtype);
65 static int add_DN_object(X509_NAME *n, char *text, const char *def,
66                          char *value, int nid, int n_min, int n_max,
67                          unsigned long chtype, int mval);
68 static int genpkey_cb(EVP_PKEY_CTX *ctx);
69 static int build_data(char *text, const char *def,
70                       char *value, int n_min, int n_max,
71                       char *buf, const int buf_size,
72                       const char *desc1, const char *desc2
73                       );
74 static int req_check_len(int len, int n_min, int n_max);
75 static int check_end(const char *str, const char *end);
76 static int join(char buf[], size_t buf_size, const char *name,
77                 const char *tail, const char *desc);
78 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
79                                     int *pkey_type, long *pkeylen,
80                                     char **palgnam, ENGINE *keygen_engine);
81
82 static const char *section = "req";
83 static CONF *req_conf = NULL;
84 static CONF *addext_conf = NULL;
85 static int batch = 0;
86
87 typedef enum OPTION_choice {
88     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
89     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
90     OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
91     OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
92     OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
93     OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
94     OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
95     OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
96     OPT_REQEXTS, OPT_PRECERT, OPT_MD,
97     OPT_SECTION,
98     OPT_R_ENUM, OPT_PROV_ENUM
99 } OPTION_CHOICE;
100
101 const OPTIONS req_options[] = {
102     OPT_SECTION("General"),
103     {"help", OPT_HELP, '-', "Display this summary"},
104 #ifndef OPENSSL_NO_ENGINE
105     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
106     {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
107      "Specify engine to be used for key generation operations"},
108 #endif
109     {"in", OPT_IN, '<', "Input file"},
110     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
111     {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
112
113     OPT_SECTION("Certificate"),
114     {"new", OPT_NEW, '-', "New request"},
115     {"config", OPT_CONFIG, '<', "Request template file"},
116     {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
117     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
118     {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
119     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
120     {"text", OPT_TEXT, '-', "Text form of request"},
121     {"x509", OPT_X509, '-',
122      "Output an x509 structure instead of a cert request"},
123     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
124     {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
125     {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
126     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
127      "Enable support for multivalued RDNs"},
128     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
129     {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
130     {"addext", OPT_ADDEXT, 's',
131      "Additional cert extension key=value pair (may be given more than once)"},
132     {"extensions", OPT_EXTENSIONS, 's',
133      "Cert extension section (override value in config file)"},
134     {"reqexts", OPT_REQEXTS, 's',
135      "Request extension section (override value in config file)"},
136     {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
137
138     OPT_SECTION("Keys and Signing"),
139     {"key", OPT_KEY, 's', "Private key to use"},
140     {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
141     {"pubkey", OPT_PUBKEY, '-', "Output public key"},
142     {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
143     {"passin", OPT_PASSIN, 's', "Private key password source"},
144     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
145     {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
146     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
147     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
148     {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
149     {"", OPT_MD, '-', "Any supported digest"},
150
151     OPT_SECTION("Output"),
152     {"out", OPT_OUT, '>', "Output file"},
153     {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
154     {"batch", OPT_BATCH, '-',
155      "Do not ask anything during request generation"},
156     {"verbose", OPT_VERBOSE, '-', "Verbose output"},
157     {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
158     {"noout", OPT_NOOUT, '-', "Do not output REQ"},
159     {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
160     {"modulus", OPT_MODULUS, '-', "RSA modulus"},
161
162     OPT_R_OPTIONS,
163     OPT_PROV_OPTIONS,
164     {NULL}
165 };
166
167
168 /*
169  * An LHASH of strings, where each string is an extension name.
170  */
171 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
172 {
173     return OPENSSL_LH_strhash((const char *)a);
174 }
175
176 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
177 {
178     return strcmp((const char *)a, (const char *)b);
179 }
180
181 static void exts_cleanup(OPENSSL_STRING *x)
182 {
183     OPENSSL_free((char *)x);
184 }
185
186 /*
187  * Is the |kv| key already duplicated?  This is remarkably tricky to get
188  * right.  Return 0 if unique, -1 on runtime error; 1 if found or a syntax
189  * error.
190  */
191 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
192 {
193     char *p;
194     size_t off;
195
196     /* Check syntax. */
197     /* Skip leading whitespace, make a copy. */
198     while (*kv && isspace(*kv))
199         if (*++kv == '\0')
200             return 1;
201     if ((p = strchr(kv, '=')) == NULL)
202         return 1;
203     off = p - kv;
204     if ((kv = OPENSSL_strdup(kv)) == NULL)
205         return -1;
206
207     /* Skip trailing space before the equal sign. */
208     for (p = kv + off; p > kv; --p)
209         if (!isspace(p[-1]))
210             break;
211     if (p == kv) {
212         OPENSSL_free(kv);
213         return 1;
214     }
215     *p = '\0';
216
217     /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
218     p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv);
219     if (p != NULL) {
220         OPENSSL_free(p);
221         return 1;
222     } else if (lh_OPENSSL_STRING_error(addexts)) {
223         OPENSSL_free(kv);
224         return -1;
225     }
226
227     return 0;
228 }
229
230 int req_main(int argc, char **argv)
231 {
232     ASN1_INTEGER *serial = NULL;
233     BIO *out = NULL;
234     ENGINE *e = NULL, *gen_eng = NULL;
235     EVP_PKEY *pkey = NULL;
236     EVP_PKEY_CTX *genctx = NULL;
237     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
238     LHASH_OF(OPENSSL_STRING) *addexts = NULL;
239     X509 *x509ss = NULL;
240     X509_REQ *req = NULL;
241     const EVP_CIPHER *cipher = NULL;
242     const EVP_MD *md_alg = NULL, *digest = NULL;
243     BIO *addext_bio = NULL;
244     char *extensions = NULL, *infile = NULL;
245     char *outfile = NULL, *keyfile = NULL;
246     char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
247     char *passin = NULL, *passout = NULL;
248     char *nofree_passin = NULL, *nofree_passout = NULL;
249     char *req_exts = NULL, *subj = NULL;
250     char *template = default_config_file, *keyout = NULL;
251     const char *keyalg = NULL;
252     OPTION_CHOICE o;
253     int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
254     int pkey_type = -1, private = 0;
255     int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
256     int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
257     int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
258     long newkey = -1;
259     unsigned long chtype = MBSTRING_ASC, reqflag = 0;
260
261 #ifndef OPENSSL_NO_DES
262     cipher = EVP_des_ede3_cbc();
263 #endif
264
265     prog = opt_init(argc, argv, req_options);
266     while ((o = opt_next()) != OPT_EOF) {
267         switch (o) {
268         case OPT_EOF:
269         case OPT_ERR:
270  opthelp:
271             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
272             goto end;
273         case OPT_HELP:
274             opt_help(req_options);
275             ret = 0;
276             goto end;
277         case OPT_INFORM:
278             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
279                 goto opthelp;
280             break;
281         case OPT_OUTFORM:
282             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
283                 goto opthelp;
284             break;
285         case OPT_ENGINE:
286             e = setup_engine(opt_arg(), 0);
287             break;
288         case OPT_KEYGEN_ENGINE:
289 #ifndef OPENSSL_NO_ENGINE
290             gen_eng = ENGINE_by_id(opt_arg());
291             if (gen_eng == NULL) {
292                 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
293                 goto opthelp;
294             }
295 #endif
296             break;
297         case OPT_KEY:
298             keyfile = opt_arg();
299             break;
300         case OPT_PUBKEY:
301             pubkey = 1;
302             break;
303         case OPT_NEW:
304             newreq = 1;
305             break;
306         case OPT_CONFIG:
307             template = opt_arg();
308             break;
309         case OPT_SECTION:
310             section = opt_arg();
311             break;
312         case OPT_KEYFORM:
313             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
314                 goto opthelp;
315             break;
316         case OPT_IN:
317             infile = opt_arg();
318             break;
319         case OPT_OUT:
320             outfile = opt_arg();
321             break;
322         case OPT_KEYOUT:
323             keyout = opt_arg();
324             break;
325         case OPT_PASSIN:
326             passargin = opt_arg();
327             break;
328         case OPT_PASSOUT:
329             passargout = opt_arg();
330             break;
331         case OPT_R_CASES:
332             if (!opt_rand(o))
333                 goto end;
334             break;
335         case OPT_PROV_CASES:
336             if (!opt_provider(o))
337                 goto end;
338             break;
339         case OPT_NEWKEY:
340             keyalg = opt_arg();
341             newreq = 1;
342             break;
343         case OPT_PKEYOPT:
344             if (pkeyopts == NULL)
345                 pkeyopts = sk_OPENSSL_STRING_new_null();
346             if (pkeyopts == NULL
347                     || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
348                 goto opthelp;
349             break;
350         case OPT_SIGOPT:
351             if (!sigopts)
352                 sigopts = sk_OPENSSL_STRING_new_null();
353             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
354                 goto opthelp;
355             break;
356         case OPT_VFYOPT:
357             if (!vfyopts)
358                 vfyopts = sk_OPENSSL_STRING_new_null();
359             if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
360                 goto opthelp;
361             break;
362         case OPT_BATCH:
363             batch = 1;
364             break;
365         case OPT_NEWHDR:
366             newhdr = 1;
367             break;
368         case OPT_MODULUS:
369             modulus = 1;
370             break;
371         case OPT_VERIFY:
372             verify = 1;
373             break;
374         case OPT_NODES:
375             nodes = 1;
376             break;
377         case OPT_NOOUT:
378             noout = 1;
379             break;
380         case OPT_VERBOSE:
381             verbose = 1;
382             break;
383         case OPT_UTF8:
384             chtype = MBSTRING_UTF8;
385             break;
386         case OPT_NAMEOPT:
387             if (!set_nameopt(opt_arg()))
388                 goto opthelp;
389             break;
390         case OPT_REQOPT:
391             if (!set_cert_ex(&reqflag, opt_arg()))
392                 goto opthelp;
393             break;
394         case OPT_TEXT:
395             text = 1;
396             break;
397         case OPT_X509:
398             x509 = 1;
399             break;
400         case OPT_DAYS:
401             days = atoi(opt_arg());
402             break;
403         case OPT_SET_SERIAL:
404             if (serial != NULL) {
405                 BIO_printf(bio_err, "Serial number supplied twice\n");
406                 goto opthelp;
407             }
408             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
409             if (serial == NULL)
410                 goto opthelp;
411             break;
412         case OPT_SUBJECT:
413             subject = 1;
414             break;
415         case OPT_SUBJ:
416             subj = opt_arg();
417             break;
418         case OPT_MULTIVALUE_RDN:
419             multirdn = 1;
420             break;
421         case OPT_ADDEXT:
422             p = opt_arg();
423             if (addexts == NULL) {
424                 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
425                 addext_bio = BIO_new(BIO_s_mem());
426                 if (addexts == NULL || addext_bio == NULL)
427                     goto end;
428             }
429             i = duplicated(addexts, p);
430             if (i == 1)
431                 goto opthelp;
432             if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
433                 goto end;
434             break;
435         case OPT_EXTENSIONS:
436             extensions = opt_arg();
437             break;
438         case OPT_REQEXTS:
439             req_exts = opt_arg();
440             break;
441         case OPT_PRECERT:
442             newreq = precert = 1;
443             break;
444         case OPT_MD:
445             if (!opt_md(opt_unknown(), &md_alg))
446                 goto opthelp;
447             digest = md_alg;
448             break;
449         }
450     }
451     argc = opt_num_rest();
452     if (argc != 0)
453         goto opthelp;
454
455     if (days && !x509)
456         BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
457     if (x509 && infile == NULL)
458         newreq = 1;
459
460     /* TODO: simplify this as pkey is still always NULL here */
461     private = newreq && (pkey == NULL) ? 1 : 0;
462
463     if (!app_passwd(passargin, passargout, &passin, &passout)) {
464         BIO_printf(bio_err, "Error getting passwords\n");
465         goto end;
466     }
467
468     if (verbose)
469         BIO_printf(bio_err, "Using configuration from %s\n", template);
470     if ((req_conf = app_load_config(template)) == NULL)
471         goto end;
472     if (addext_bio != NULL) {
473         if (verbose)
474             BIO_printf(bio_err,
475                        "Using additional configuration from command line\n");
476         if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
477             goto end;
478     }
479     if (template != default_config_file && !app_load_modules(req_conf))
480         goto end;
481
482     if (req_conf != NULL) {
483         p = NCONF_get_string(req_conf, NULL, "oid_file");
484         if (p == NULL)
485             ERR_clear_error();
486         if (p != NULL) {
487             BIO *oid_bio;
488
489             oid_bio = BIO_new_file(p, "r");
490             if (oid_bio == NULL) {
491                 /*-
492                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
493                 ERR_print_errors(bio_err);
494                 */
495             } else {
496                 OBJ_create_objects(oid_bio);
497                 BIO_free(oid_bio);
498             }
499         }
500     }
501     if (!add_oid_section(req_conf))
502         goto end;
503
504     if (md_alg == NULL) {
505         p = NCONF_get_string(req_conf, section, "default_md");
506         if (p == NULL) {
507             ERR_clear_error();
508         } else {
509             if (!opt_md(p, &md_alg))
510                 goto opthelp;
511             digest = md_alg;
512         }
513     }
514
515     if (extensions == NULL) {
516         extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
517         if (extensions == NULL)
518             ERR_clear_error();
519     }
520     if (extensions != NULL) {
521         /* Check syntax of file */
522         X509V3_CTX ctx;
523         X509V3_set_ctx_test(&ctx);
524         X509V3_set_nconf(&ctx, req_conf);
525         if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
526             BIO_printf(bio_err,
527                        "Error Loading extension section %s\n", extensions);
528             goto end;
529         }
530     }
531     if (addext_conf != NULL) {
532         /* Check syntax of command line extensions */
533         X509V3_CTX ctx;
534         X509V3_set_ctx_test(&ctx);
535         X509V3_set_nconf(&ctx, addext_conf);
536         if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
537             BIO_printf(bio_err, "Error Loading command line extensions\n");
538             goto end;
539         }
540     }
541
542     if (passin == NULL) {
543         passin = nofree_passin =
544             NCONF_get_string(req_conf, section, "input_password");
545         if (passin == NULL)
546             ERR_clear_error();
547     }
548
549     if (passout == NULL) {
550         passout = nofree_passout =
551             NCONF_get_string(req_conf, section, "output_password");
552         if (passout == NULL)
553             ERR_clear_error();
554     }
555
556     p = NCONF_get_string(req_conf, section, STRING_MASK);
557     if (p == NULL)
558         ERR_clear_error();
559
560     if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
561         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
562         goto end;
563     }
564
565     if (chtype != MBSTRING_UTF8) {
566         p = NCONF_get_string(req_conf, section, UTF8_IN);
567         if (p == NULL)
568             ERR_clear_error();
569         else if (strcmp(p, "yes") == 0)
570             chtype = MBSTRING_UTF8;
571     }
572
573     if (req_exts == NULL) {
574         req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
575         if (req_exts == NULL)
576             ERR_clear_error();
577     }
578     if (req_exts != NULL) {
579         /* Check syntax of file */
580         X509V3_CTX ctx;
581         X509V3_set_ctx_test(&ctx);
582         X509V3_set_nconf(&ctx, req_conf);
583         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
584             BIO_printf(bio_err,
585                        "Error Loading request extension section %s\n",
586                        req_exts);
587             goto end;
588         }
589     }
590
591     if (keyfile != NULL) {
592         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
593         if (pkey == NULL)
594             goto end;
595         app_RAND_load_conf(req_conf, section);
596     }
597
598     if (newreq && (pkey == NULL)) {
599         app_RAND_load_conf(req_conf, section);
600
601         if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
602             newkey = DEFAULT_KEY_LENGTH;
603         }
604
605         if (keyalg != NULL) {
606             genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
607                                     &keyalgstr, gen_eng);
608             if (genctx == NULL)
609                 goto end;
610         }
611
612         if (newkey < MIN_KEY_LENGTH
613             && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
614             BIO_printf(bio_err, "private key length is too short,\n");
615             BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
616                        MIN_KEY_LENGTH, newkey);
617             goto end;
618         }
619
620         if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
621             BIO_printf(bio_err,
622                        "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
623                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
624                        OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
625
626 #ifndef OPENSSL_NO_DSA
627         if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
628             BIO_printf(bio_err,
629                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
630                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
631                        OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
632 #endif
633
634         if (genctx == NULL) {
635             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
636                                     &keyalgstr, gen_eng);
637             if (!genctx)
638                 goto end;
639         }
640
641         if (pkeyopts != NULL) {
642             char *genopt;
643             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
644                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
645                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
646                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
647                     ERR_print_errors(bio_err);
648                     goto end;
649                 }
650             }
651         }
652
653         if (pkey_type == EVP_PKEY_EC) {
654             BIO_printf(bio_err, "Generating an EC private key\n");
655         } else {
656             BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
657         }
658
659         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
660         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
661
662         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
663             BIO_puts(bio_err, "Error Generating Key\n");
664             goto end;
665         }
666
667         EVP_PKEY_CTX_free(genctx);
668         genctx = NULL;
669
670         if (keyout == NULL) {
671             keyout = NCONF_get_string(req_conf, section, KEYFILE);
672             if (keyout == NULL)
673                 ERR_clear_error();
674         }
675
676         if (keyout == NULL)
677             BIO_printf(bio_err, "writing new private key to stdout\n");
678         else
679             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
680         out = bio_open_owner(keyout, outformat, private);
681         if (out == NULL)
682             goto end;
683
684         p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
685         if (p == NULL) {
686             ERR_clear_error();
687             p = NCONF_get_string(req_conf, section, "encrypt_key");
688             if (p == NULL)
689                 ERR_clear_error();
690         }
691         if ((p != NULL) && (strcmp(p, "no") == 0))
692             cipher = NULL;
693         if (nodes)
694             cipher = NULL;
695
696         i = 0;
697  loop:
698         assert(private);
699         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
700                                       NULL, 0, NULL, passout)) {
701             if ((ERR_GET_REASON(ERR_peek_error()) ==
702                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
703                 ERR_clear_error();
704                 i++;
705                 goto loop;
706             }
707             goto end;
708         }
709         BIO_free(out);
710         out = NULL;
711         BIO_printf(bio_err, "-----\n");
712     }
713
714     if (!newreq) {
715         req = load_csr(infile, informat, "X509 request");
716         if (req == NULL)
717             goto end;
718     }
719
720     if (newreq || x509) {
721         if (pkey == NULL) {
722             BIO_printf(bio_err, "you need to specify a private key\n");
723             goto end;
724         }
725
726         if (req == NULL) {
727             req = X509_REQ_new();
728             if (req == NULL) {
729                 goto end;
730             }
731
732             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
733             subj = NULL;        /* done processing '-subj' option */
734             if (!i) {
735                 BIO_printf(bio_err, "problems making Certificate Request\n");
736                 goto end;
737             }
738         }
739         if (x509) {
740             EVP_PKEY *tmppkey;
741             X509V3_CTX ext_ctx;
742             if ((x509ss = X509_new()) == NULL)
743                 goto end;
744
745             /* Set version to V3 */
746             if ((extensions != NULL || addext_conf != NULL)
747                 && !X509_set_version(x509ss, 2))
748                 goto end;
749             if (serial != NULL) {
750                 if (!X509_set_serialNumber(x509ss, serial))
751                     goto end;
752             } else {
753                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
754                     goto end;
755             }
756
757             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
758                 goto end;
759             if (days == 0) {
760                 /* set default days if it's not specified */
761                 days = 30;
762             }
763             if (!set_cert_times(x509ss, NULL, NULL, days))
764                 goto end;
765             if (!X509_set_subject_name
766                 (x509ss, X509_REQ_get_subject_name(req)))
767                 goto end;
768             tmppkey = X509_REQ_get0_pubkey(req);
769             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
770                 goto end;
771
772             /* Set up V3 context struct */
773
774             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
775             X509V3_set_nconf(&ext_ctx, req_conf);
776
777             /* Add extensions */
778             if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
779                                                             &ext_ctx, extensions,
780                                                             x509ss)) {
781                 BIO_printf(bio_err, "Error Loading extension section %s\n",
782                            extensions);
783                 goto end;
784             }
785             if (addext_conf != NULL
786                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
787                                          x509ss)) {
788                 BIO_printf(bio_err, "Error Loading command line extensions\n");
789                 goto end;
790             }
791
792             /* If a pre-cert was requested, we need to add a poison extension */
793             if (precert) {
794                 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
795                     != 1) {
796                     BIO_printf(bio_err, "Error adding poison extension\n");
797                     goto end;
798                 }
799             }
800
801             i = do_X509_sign(x509ss, pkey, digest, sigopts);
802             if (!i) {
803                 ERR_print_errors(bio_err);
804                 goto end;
805             }
806         } else {
807             X509V3_CTX ext_ctx;
808
809             /* Set up V3 context struct */
810
811             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
812             X509V3_set_nconf(&ext_ctx, req_conf);
813
814             /* Add extensions */
815             if (req_exts != NULL
816                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
817                                              req_exts, req)) {
818                 BIO_printf(bio_err, "Error Loading extension section %s\n",
819                            req_exts);
820                 goto end;
821             }
822             if (addext_conf != NULL
823                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
824                                              req)) {
825                 BIO_printf(bio_err, "Error Loading command line extensions\n");
826                 goto end;
827             }
828             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
829             if (!i) {
830                 ERR_print_errors(bio_err);
831                 goto end;
832             }
833         }
834     }
835
836     if (subj && x509) {
837         BIO_printf(bio_err, "Cannot modify certificate subject\n");
838         goto end;
839     }
840
841     if (subj && !x509) {
842         if (verbose) {
843             BIO_printf(bio_err, "Modifying Request's Subject\n");
844             print_name(bio_err, "old subject=",
845                        X509_REQ_get_subject_name(req), get_nameopt());
846         }
847
848         if (build_subject(req, subj, chtype, multirdn) == 0) {
849             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
850             ret = 1;
851             goto end;
852         }
853
854         if (verbose) {
855             print_name(bio_err, "new subject=",
856                        X509_REQ_get_subject_name(req), get_nameopt());
857         }
858     }
859
860     if (verify && !x509) {
861         EVP_PKEY *tpubkey = pkey;
862
863         if (tpubkey == NULL) {
864             tpubkey = X509_REQ_get0_pubkey(req);
865             if (tpubkey == NULL)
866                 goto end;
867         }
868
869         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
870
871         if (i < 0) {
872             goto end;
873         } else if (i == 0) {
874             BIO_printf(bio_err, "verify failure\n");
875             ERR_print_errors(bio_err);
876         } else {                 /* if (i > 0) */
877             BIO_printf(bio_err, "verify OK\n");
878         }
879     }
880
881     if (noout && !text && !modulus && !subject && !pubkey) {
882         ret = 0;
883         goto end;
884     }
885
886     out = bio_open_default(outfile,
887                            keyout != NULL && outfile != NULL &&
888                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
889                            outformat);
890     if (out == NULL)
891         goto end;
892
893     if (pubkey) {
894         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
895
896         if (tpubkey == NULL) {
897             BIO_printf(bio_err, "Error getting public key\n");
898             ERR_print_errors(bio_err);
899             goto end;
900         }
901         PEM_write_bio_PUBKEY(out, tpubkey);
902     }
903
904     if (text) {
905         if (x509)
906             ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
907         else
908             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
909
910         if (ret == 0) {
911             if (x509)
912               BIO_printf(bio_err, "Error printing certificate\n");
913             else
914               BIO_printf(bio_err, "Error printing certificate request\n");
915
916             ERR_print_errors(bio_err);
917             goto end;
918         }
919     }
920
921     if (subject) {
922         if (x509)
923             print_name(out, "subject=", X509_get_subject_name(x509ss),
924                        get_nameopt());
925         else
926             print_name(out, "subject=", X509_REQ_get_subject_name(req),
927                        get_nameopt());
928     }
929
930     if (modulus) {
931         EVP_PKEY *tpubkey;
932
933         if (x509)
934             tpubkey = X509_get0_pubkey(x509ss);
935         else
936             tpubkey = X509_REQ_get0_pubkey(req);
937         if (tpubkey == NULL) {
938             fprintf(stdout, "Modulus=unavailable\n");
939             goto end;
940         }
941         fprintf(stdout, "Modulus=");
942 #ifndef OPENSSL_NO_RSA
943         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
944             const BIGNUM *n;
945             RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
946             BN_print(out, n);
947         } else
948 #endif
949             fprintf(stdout, "Wrong Algorithm type");
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     ENGINE_free(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)) == 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         ENGINE_finish(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         ENGINE_finish(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 #ifndef OPENSSL_NO_RSA
1597     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1598         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1599             BIO_puts(bio_err, "Error setting RSA keysize\n");
1600             ERR_print_errors(bio_err);
1601             EVP_PKEY_CTX_free(gctx);
1602             return NULL;
1603         }
1604     }
1605 #endif
1606
1607     return gctx;
1608 }
1609
1610 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1611 {
1612     char c = '*';
1613     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1614     int p;
1615     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1616     if (p == 0)
1617         c = '.';
1618     if (p == 1)
1619         c = '+';
1620     if (p == 2)
1621         c = '*';
1622     if (p == 3)
1623         c = '\n';
1624     BIO_write(b, &c, 1);
1625     (void)BIO_flush(b);
1626     return 1;
1627 }
1628
1629 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1630 {
1631     int i;
1632
1633     if (opts == NULL)
1634         return 1;
1635
1636     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1637         char *opt = sk_OPENSSL_STRING_value(opts, i);
1638         if (pkey_ctrl_string(pkctx, opt) <= 0) {
1639             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1640             ERR_print_errors(bio_err);
1641             return 0;
1642         }
1643     }
1644
1645     return 1;
1646 }
1647
1648 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1649 {
1650     int i;
1651
1652     if (opts == NULL)
1653         return 1;
1654
1655     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1656         char *opt = sk_OPENSSL_STRING_value(opts, i);
1657         if (x509_ctrl_string(x, opt) <= 0) {
1658             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1659             ERR_print_errors(bio_err);
1660             return 0;
1661         }
1662     }
1663
1664     return 1;
1665 }
1666
1667 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1668 {
1669     int i;
1670
1671     if (opts == NULL)
1672         return 1;
1673
1674     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1675         char *opt = sk_OPENSSL_STRING_value(opts, i);
1676         if (x509_req_ctrl_string(x, opt) <= 0) {
1677             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1678             ERR_print_errors(bio_err);
1679             return 0;
1680         }
1681     }
1682
1683     return 1;
1684 }
1685
1686 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1687                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1688 {
1689     EVP_PKEY_CTX *pkctx = NULL;
1690     int def_nid;
1691
1692     if (ctx == NULL)
1693         return 0;
1694     /*
1695      * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1696      * for this algorithm.
1697      */
1698     if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1699             && def_nid == NID_undef) {
1700         /* The signing algorithm requires there to be no digest */
1701         md = NULL;
1702     }
1703     return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1704         && do_pkey_ctx_init(pkctx, sigopts);
1705 }
1706
1707 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1708                  STACK_OF(OPENSSL_STRING) *sigopts)
1709 {
1710     int rv = 0;
1711     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1712
1713     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1714         rv = (X509_sign_ctx(x, mctx) > 0);
1715     EVP_MD_CTX_free(mctx);
1716     return rv;
1717 }
1718
1719 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1720                      STACK_OF(OPENSSL_STRING) *sigopts)
1721 {
1722     int rv = 0;
1723     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1724
1725     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1726         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1727     EVP_MD_CTX_free(mctx);
1728     return rv;
1729 }
1730
1731 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1732 {
1733     int rv = 0;
1734
1735     if (do_x509_init(x, vfyopts) > 0)
1736         rv = (X509_verify(x, pkey) > 0);
1737     return rv;
1738 }
1739
1740 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1741                        STACK_OF(OPENSSL_STRING) *vfyopts)
1742 {
1743     int rv = 0;
1744
1745     if (do_x509_req_init(x, vfyopts) > 0)
1746         rv = (X509_REQ_verify(x, pkey) > 0);
1747     return rv;
1748 }
1749
1750 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1751                      STACK_OF(OPENSSL_STRING) *sigopts)
1752 {
1753     int rv = 0;
1754     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1755
1756     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1757         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1758     EVP_MD_CTX_free(mctx);
1759     return rv;
1760 }