APPS: Reduce deprecation warning suppression - ENGINE
[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                 goto opthelp;
431             if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
432                 goto end;
433             break;
434         case OPT_EXTENSIONS:
435             extensions = opt_arg();
436             break;
437         case OPT_REQEXTS:
438             req_exts = opt_arg();
439             break;
440         case OPT_PRECERT:
441             newreq = precert = 1;
442             break;
443         case OPT_MD:
444             if (!opt_md(opt_unknown(), &md_alg))
445                 goto opthelp;
446             digest = md_alg;
447             break;
448         }
449     }
450     argc = opt_num_rest();
451     if (argc != 0)
452         goto opthelp;
453
454     if (days && !x509)
455         BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
456     if (x509 && infile == NULL)
457         newreq = 1;
458
459     /* TODO: simplify this as pkey is still always NULL here */
460     private = newreq && (pkey == NULL) ? 1 : 0;
461
462     if (!app_passwd(passargin, passargout, &passin, &passout)) {
463         BIO_printf(bio_err, "Error getting passwords\n");
464         goto end;
465     }
466
467     if (verbose)
468         BIO_printf(bio_err, "Using configuration from %s\n", template);
469     if ((req_conf = app_load_config(template)) == NULL)
470         goto end;
471     if (addext_bio != NULL) {
472         if (verbose)
473             BIO_printf(bio_err,
474                        "Using additional configuration from command line\n");
475         if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
476             goto end;
477     }
478     if (template != default_config_file && !app_load_modules(req_conf))
479         goto end;
480
481     if (req_conf != NULL) {
482         p = NCONF_get_string(req_conf, NULL, "oid_file");
483         if (p == NULL)
484             ERR_clear_error();
485         if (p != NULL) {
486             BIO *oid_bio;
487
488             oid_bio = BIO_new_file(p, "r");
489             if (oid_bio == NULL) {
490                 /*-
491                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
492                 ERR_print_errors(bio_err);
493                 */
494             } else {
495                 OBJ_create_objects(oid_bio);
496                 BIO_free(oid_bio);
497             }
498         }
499     }
500     if (!add_oid_section(req_conf))
501         goto end;
502
503     if (md_alg == NULL) {
504         p = NCONF_get_string(req_conf, section, "default_md");
505         if (p == NULL) {
506             ERR_clear_error();
507         } else {
508             if (!opt_md(p, &md_alg))
509                 goto opthelp;
510             digest = md_alg;
511         }
512     }
513
514     if (extensions == NULL) {
515         extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
516         if (extensions == NULL)
517             ERR_clear_error();
518     }
519     if (extensions != NULL) {
520         /* Check syntax of file */
521         X509V3_CTX ctx;
522         X509V3_set_ctx_test(&ctx);
523         X509V3_set_nconf(&ctx, req_conf);
524         if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
525             BIO_printf(bio_err,
526                        "Error Loading extension section %s\n", extensions);
527             goto end;
528         }
529     }
530     if (addext_conf != NULL) {
531         /* Check syntax of command line extensions */
532         X509V3_CTX ctx;
533         X509V3_set_ctx_test(&ctx);
534         X509V3_set_nconf(&ctx, addext_conf);
535         if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
536             BIO_printf(bio_err, "Error Loading command line extensions\n");
537             goto end;
538         }
539     }
540
541     if (passin == NULL) {
542         passin = nofree_passin =
543             NCONF_get_string(req_conf, section, "input_password");
544         if (passin == NULL)
545             ERR_clear_error();
546     }
547
548     if (passout == NULL) {
549         passout = nofree_passout =
550             NCONF_get_string(req_conf, section, "output_password");
551         if (passout == NULL)
552             ERR_clear_error();
553     }
554
555     p = NCONF_get_string(req_conf, section, STRING_MASK);
556     if (p == NULL)
557         ERR_clear_error();
558
559     if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
560         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
561         goto end;
562     }
563
564     if (chtype != MBSTRING_UTF8) {
565         p = NCONF_get_string(req_conf, section, UTF8_IN);
566         if (p == NULL)
567             ERR_clear_error();
568         else if (strcmp(p, "yes") == 0)
569             chtype = MBSTRING_UTF8;
570     }
571
572     if (req_exts == NULL) {
573         req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
574         if (req_exts == NULL)
575             ERR_clear_error();
576     }
577     if (req_exts != NULL) {
578         /* Check syntax of file */
579         X509V3_CTX ctx;
580         X509V3_set_ctx_test(&ctx);
581         X509V3_set_nconf(&ctx, req_conf);
582         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
583             BIO_printf(bio_err,
584                        "Error Loading request extension section %s\n",
585                        req_exts);
586             goto end;
587         }
588     }
589
590     if (keyfile != NULL) {
591         pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
592         if (pkey == NULL)
593             goto end;
594         app_RAND_load_conf(req_conf, section);
595     }
596
597     if (newreq && (pkey == NULL)) {
598         app_RAND_load_conf(req_conf, section);
599
600         if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
601             newkey = DEFAULT_KEY_LENGTH;
602         }
603
604         if (keyalg != NULL) {
605             genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
606                                     &keyalgstr, gen_eng);
607             if (genctx == NULL)
608                 goto end;
609         }
610
611         if (newkey < MIN_KEY_LENGTH
612             && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
613             BIO_printf(bio_err, "private key length is too short,\n");
614             BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
615                        MIN_KEY_LENGTH, newkey);
616             goto end;
617         }
618
619         if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
620             BIO_printf(bio_err,
621                        "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
622                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
623                        OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
624
625 #ifndef OPENSSL_NO_DSA
626         if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
627             BIO_printf(bio_err,
628                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
629                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
630                        OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
631 #endif
632
633         if (genctx == NULL) {
634             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
635                                     &keyalgstr, gen_eng);
636             if (!genctx)
637                 goto end;
638         }
639
640         if (pkeyopts != NULL) {
641             char *genopt;
642             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
643                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
644                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
645                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
646                     ERR_print_errors(bio_err);
647                     goto end;
648                 }
649             }
650         }
651
652         if (pkey_type == EVP_PKEY_EC) {
653             BIO_printf(bio_err, "Generating an EC private key\n");
654         } else {
655             BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
656         }
657
658         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
659         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
660
661         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
662             BIO_puts(bio_err, "Error Generating Key\n");
663             goto end;
664         }
665
666         EVP_PKEY_CTX_free(genctx);
667         genctx = NULL;
668
669         if (keyout == NULL) {
670             keyout = NCONF_get_string(req_conf, section, KEYFILE);
671             if (keyout == NULL)
672                 ERR_clear_error();
673         }
674
675         if (keyout == NULL)
676             BIO_printf(bio_err, "writing new private key to stdout\n");
677         else
678             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
679         out = bio_open_owner(keyout, outformat, private);
680         if (out == NULL)
681             goto end;
682
683         p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
684         if (p == NULL) {
685             ERR_clear_error();
686             p = NCONF_get_string(req_conf, section, "encrypt_key");
687             if (p == NULL)
688                 ERR_clear_error();
689         }
690         if ((p != NULL) && (strcmp(p, "no") == 0))
691             cipher = NULL;
692         if (noenc)
693             cipher = NULL;
694
695         i = 0;
696  loop:
697         assert(private);
698         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
699                                       NULL, 0, NULL, passout)) {
700             if ((ERR_GET_REASON(ERR_peek_error()) ==
701                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
702                 ERR_clear_error();
703                 i++;
704                 goto loop;
705             }
706             goto end;
707         }
708         BIO_free(out);
709         out = NULL;
710         BIO_printf(bio_err, "-----\n");
711     }
712
713     if (!newreq) {
714         req = load_csr(infile, informat, "X509 request");
715         if (req == NULL)
716             goto end;
717     }
718
719     if (newreq || x509) {
720         if (pkey == NULL) {
721             BIO_printf(bio_err, "you need to specify a private key\n");
722             goto end;
723         }
724
725         if (req == NULL) {
726             req = X509_REQ_new();
727             if (req == NULL) {
728                 goto end;
729             }
730
731             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
732             subj = NULL;        /* done processing '-subj' option */
733             if (!i) {
734                 BIO_printf(bio_err, "problems making Certificate Request\n");
735                 goto end;
736             }
737         }
738         if (x509) {
739             EVP_PKEY *tmppkey;
740             X509V3_CTX ext_ctx;
741             if ((x509ss = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
742                 goto end;
743
744             /* Set version to V3 */
745             if ((extensions != NULL || addext_conf != NULL)
746                 && !X509_set_version(x509ss, 2))
747                 goto end;
748             if (serial != NULL) {
749                 if (!X509_set_serialNumber(x509ss, serial))
750                     goto end;
751             } else {
752                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
753                     goto end;
754             }
755
756             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
757                 goto end;
758             if (days == 0) {
759                 /* set default days if it's not specified */
760                 days = 30;
761             }
762             if (!set_cert_times(x509ss, NULL, NULL, days))
763                 goto end;
764             if (!X509_set_subject_name
765                 (x509ss, X509_REQ_get_subject_name(req)))
766                 goto end;
767             tmppkey = X509_REQ_get0_pubkey(req);
768             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
769                 goto end;
770
771             /* Set up V3 context struct */
772
773             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
774             X509V3_set_nconf(&ext_ctx, req_conf);
775
776             /* Add extensions */
777             if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
778                                                             &ext_ctx, extensions,
779                                                             x509ss)) {
780                 BIO_printf(bio_err, "Error Loading extension section %s\n",
781                            extensions);
782                 goto end;
783             }
784             if (addext_conf != NULL
785                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
786                                          x509ss)) {
787                 BIO_printf(bio_err, "Error Loading command line extensions\n");
788                 goto end;
789             }
790
791             /* If a pre-cert was requested, we need to add a poison extension */
792             if (precert) {
793                 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
794                     != 1) {
795                     BIO_printf(bio_err, "Error adding poison extension\n");
796                     goto end;
797                 }
798             }
799
800             i = do_X509_sign(x509ss, pkey, digest, sigopts);
801             if (!i) {
802                 ERR_print_errors(bio_err);
803                 goto end;
804             }
805         } else {
806             X509V3_CTX ext_ctx;
807
808             /* Set up V3 context struct */
809
810             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
811             X509V3_set_nconf(&ext_ctx, req_conf);
812
813             /* Add extensions */
814             if (req_exts != NULL
815                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
816                                              req_exts, req)) {
817                 BIO_printf(bio_err, "Error Loading extension section %s\n",
818                            req_exts);
819                 goto end;
820             }
821             if (addext_conf != NULL
822                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
823                                              req)) {
824                 BIO_printf(bio_err, "Error Loading command line extensions\n");
825                 goto end;
826             }
827             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
828             if (!i) {
829                 ERR_print_errors(bio_err);
830                 goto end;
831             }
832         }
833     }
834
835     if (subj && x509) {
836         BIO_printf(bio_err, "Cannot modify certificate subject\n");
837         goto end;
838     }
839
840     if (subj && !x509) {
841         if (verbose) {
842             BIO_printf(bio_err, "Modifying Request's Subject\n");
843             print_name(bio_err, "old subject=",
844                        X509_REQ_get_subject_name(req), get_nameopt());
845         }
846
847         if (build_subject(req, subj, chtype, multirdn) == 0) {
848             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
849             ret = 1;
850             goto end;
851         }
852
853         if (verbose) {
854             print_name(bio_err, "new subject=",
855                        X509_REQ_get_subject_name(req), get_nameopt());
856         }
857     }
858
859     if (verify && !x509) {
860         EVP_PKEY *tpubkey = pkey;
861
862         if (tpubkey == NULL) {
863             tpubkey = X509_REQ_get0_pubkey(req);
864             if (tpubkey == NULL)
865                 goto end;
866         }
867
868         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
869
870         if (i < 0) {
871             goto end;
872         } else if (i == 0) {
873             BIO_printf(bio_err, "verify failure\n");
874             ERR_print_errors(bio_err);
875         } else {                 /* if (i > 0) */
876             BIO_printf(bio_err, "verify OK\n");
877         }
878     }
879
880     if (noout && !text && !modulus && !subject && !pubkey) {
881         ret = 0;
882         goto end;
883     }
884
885     out = bio_open_default(outfile,
886                            keyout != NULL && outfile != NULL &&
887                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
888                            outformat);
889     if (out == NULL)
890         goto end;
891
892     if (pubkey) {
893         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
894
895         if (tpubkey == NULL) {
896             BIO_printf(bio_err, "Error getting public key\n");
897             ERR_print_errors(bio_err);
898             goto end;
899         }
900         PEM_write_bio_PUBKEY(out, tpubkey);
901     }
902
903     if (text) {
904         if (x509)
905             ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
906         else
907             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
908
909         if (ret == 0) {
910             if (x509)
911               BIO_printf(bio_err, "Error printing certificate\n");
912             else
913               BIO_printf(bio_err, "Error printing certificate request\n");
914
915             ERR_print_errors(bio_err);
916             goto end;
917         }
918     }
919
920     if (subject) {
921         if (x509)
922             print_name(out, "subject=", X509_get_subject_name(x509ss),
923                        get_nameopt());
924         else
925             print_name(out, "subject=", X509_REQ_get_subject_name(req),
926                        get_nameopt());
927     }
928
929     if (modulus) {
930         EVP_PKEY *tpubkey;
931
932         if (x509)
933             tpubkey = X509_get0_pubkey(x509ss);
934         else
935             tpubkey = X509_REQ_get0_pubkey(req);
936         if (tpubkey == NULL) {
937             fprintf(stdout, "Modulus=unavailable\n");
938             goto end;
939         }
940         fprintf(stdout, "Modulus=");
941 #ifndef OPENSSL_NO_RSA
942         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
943             const BIGNUM *n;
944             RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
945             BN_print(out, n);
946         } else
947 #endif
948             fprintf(stdout, "Wrong Algorithm type");
949         fprintf(stdout, "\n");
950     }
951
952     if (!noout && !x509) {
953         if (outformat == FORMAT_ASN1)
954             i = i2d_X509_REQ_bio(out, req);
955         else if (newhdr)
956             i = PEM_write_bio_X509_REQ_NEW(out, req);
957         else
958             i = PEM_write_bio_X509_REQ(out, req);
959         if (!i) {
960             BIO_printf(bio_err, "unable to write X509 request\n");
961             goto end;
962         }
963     }
964     if (!noout && x509 && (x509ss != NULL)) {
965         if (outformat == FORMAT_ASN1)
966             i = i2d_X509_bio(out, x509ss);
967         else
968             i = PEM_write_bio_X509(out, x509ss);
969         if (!i) {
970             BIO_printf(bio_err, "unable to write X509 certificate\n");
971             goto end;
972         }
973     }
974     ret = 0;
975  end:
976     if (ret) {
977         ERR_print_errors(bio_err);
978     }
979     NCONF_free(req_conf);
980     NCONF_free(addext_conf);
981     BIO_free(addext_bio);
982     BIO_free_all(out);
983     EVP_PKEY_free(pkey);
984     EVP_PKEY_CTX_free(genctx);
985     sk_OPENSSL_STRING_free(pkeyopts);
986     sk_OPENSSL_STRING_free(sigopts);
987     sk_OPENSSL_STRING_free(vfyopts);
988     lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
989     lh_OPENSSL_STRING_free(addexts);
990 #ifndef OPENSSL_NO_ENGINE
991     release_engine(gen_eng);
992 #endif
993     OPENSSL_free(keyalgstr);
994     X509_REQ_free(req);
995     X509_free(x509ss);
996     ASN1_INTEGER_free(serial);
997     release_engine(e);
998     if (passin != nofree_passin)
999         OPENSSL_free(passin);
1000     if (passout != nofree_passout)
1001         OPENSSL_free(passout);
1002     return ret;
1003 }
1004
1005 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1006                     int attribs, unsigned long chtype)
1007 {
1008     int ret = 0, i;
1009     char no_prompt = 0;
1010     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1011     char *tmp, *dn_sect, *attr_sect;
1012
1013     tmp = NCONF_get_string(req_conf, section, PROMPT);
1014     if (tmp == NULL)
1015         ERR_clear_error();
1016     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1017         no_prompt = 1;
1018
1019     dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1020     if (dn_sect == NULL) {
1021         BIO_printf(bio_err, "unable to find '%s' in config\n",
1022                    DISTINGUISHED_NAME);
1023         goto err;
1024     }
1025     dn_sk = NCONF_get_section(req_conf, dn_sect);
1026     if (dn_sk == NULL) {
1027         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1028         goto err;
1029     }
1030
1031     attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1032     if (attr_sect == NULL) {
1033         ERR_clear_error();
1034         attr_sk = NULL;
1035     } else {
1036         attr_sk = NCONF_get_section(req_conf, attr_sect);
1037         if (attr_sk == NULL) {
1038             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1039             goto err;
1040         }
1041     }
1042
1043     /* setup version number */
1044     if (!X509_REQ_set_version(req, 0L))
1045         goto err;               /* version 1 */
1046
1047     if (subj)
1048         i = build_subject(req, subj, chtype, multirdn);
1049     else if (no_prompt)
1050         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1051     else
1052         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1053                         chtype);
1054     if (!i)
1055         goto err;
1056
1057     if (!X509_REQ_set_pubkey(req, pkey))
1058         goto err;
1059
1060     ret = 1;
1061  err:
1062     return ret;
1063 }
1064
1065 /*
1066  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1067  * where characters may be escaped by \
1068  */
1069 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1070                          int multirdn)
1071 {
1072     X509_NAME *n;
1073
1074     if ((n = parse_name(subject, chtype, multirdn, "subject")) == NULL)
1075         return 0;
1076
1077     if (!X509_REQ_set_subject_name(req, n)) {
1078         X509_NAME_free(n);
1079         return 0;
1080     }
1081     X509_NAME_free(n);
1082     return 1;
1083 }
1084
1085 static int prompt_info(X509_REQ *req,
1086                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1087                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1088                        int attribs, unsigned long chtype)
1089 {
1090     int i;
1091     char *p, *q;
1092     char buf[100];
1093     int nid, mval;
1094     long n_min, n_max;
1095     char *type, *value;
1096     const char *def;
1097     CONF_VALUE *v;
1098     X509_NAME *subj = X509_REQ_get_subject_name(req);
1099
1100     if (!batch) {
1101         BIO_printf(bio_err,
1102                    "You are about to be asked to enter information that will be incorporated\n");
1103         BIO_printf(bio_err, "into your certificate request.\n");
1104         BIO_printf(bio_err,
1105                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1106         BIO_printf(bio_err,
1107                    "There are quite a few fields but you can leave some blank\n");
1108         BIO_printf(bio_err,
1109                    "For some fields there will be a default value,\n");
1110         BIO_printf(bio_err,
1111                    "If you enter '.', the field will be left blank.\n");
1112         BIO_printf(bio_err, "-----\n");
1113     }
1114
1115     if (sk_CONF_VALUE_num(dn_sk)) {
1116         i = -1;
1117  start:
1118         for ( ; ; ) {
1119             i++;
1120             if (sk_CONF_VALUE_num(dn_sk) <= i)
1121                 break;
1122
1123             v = sk_CONF_VALUE_value(dn_sk, i);
1124             p = q = NULL;
1125             type = v->name;
1126             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1127                 !check_end(type, "_default") || !check_end(type, "_value"))
1128                 continue;
1129             /*
1130              * Skip past any leading X. X: X, etc to allow for multiple
1131              * instances
1132              */
1133             for (p = v->name; *p; p++)
1134                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1135                     p++;
1136                     if (*p)
1137                         type = p;
1138                     break;
1139                 }
1140             if (*type == '+') {
1141                 mval = -1;
1142                 type++;
1143             } else {
1144                 mval = 0;
1145             }
1146             /* If OBJ not recognised ignore it */
1147             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1148                 goto start;
1149             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1150                 return 0;
1151             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1152                 ERR_clear_error();
1153                 def = "";
1154             }
1155
1156             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1157                 return 0;
1158             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1159                 ERR_clear_error();
1160                 value = NULL;
1161             }
1162
1163             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1164                 return 0;
1165             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1166                 ERR_clear_error();
1167                 n_min = -1;
1168             }
1169
1170
1171             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1172                 return 0;
1173             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1174                 ERR_clear_error();
1175                 n_max = -1;
1176             }
1177
1178             if (!add_DN_object(subj, v->value, def, value, nid,
1179                                n_min, n_max, chtype, mval))
1180                 return 0;
1181         }
1182         if (X509_NAME_entry_count(subj) == 0) {
1183             BIO_printf(bio_err, "error, no objects specified in config file\n");
1184             return 0;
1185         }
1186
1187         if (attribs) {
1188             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1189                 && (!batch)) {
1190                 BIO_printf(bio_err,
1191                            "\nPlease enter the following 'extra' attributes\n");
1192                 BIO_printf(bio_err,
1193                            "to be sent with your certificate request\n");
1194             }
1195
1196             i = -1;
1197  start2:
1198             for ( ; ; ) {
1199                 i++;
1200                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1201                     break;
1202
1203                 v = sk_CONF_VALUE_value(attr_sk, i);
1204                 type = v->name;
1205                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1206                     goto start2;
1207
1208                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1209                     return 0;
1210                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1211                     == NULL) {
1212                     ERR_clear_error();
1213                     def = "";
1214                 }
1215
1216                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1217                     return 0;
1218                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1219                     == NULL) {
1220                     ERR_clear_error();
1221                     value = NULL;
1222                 }
1223
1224                 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1225                     return 0;
1226                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1227                     ERR_clear_error();
1228                     n_min = -1;
1229                 }
1230
1231                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1232                     return 0;
1233                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1234                     ERR_clear_error();
1235                     n_max = -1;
1236                 }
1237
1238                 if (!add_attribute_object(req,
1239                                           v->value, def, value, nid, n_min,
1240                                           n_max, chtype))
1241                     return 0;
1242             }
1243         }
1244     } else {
1245         BIO_printf(bio_err, "No template, please set one up.\n");
1246         return 0;
1247     }
1248
1249     return 1;
1250
1251 }
1252
1253 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1254                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1255                      unsigned long chtype)
1256 {
1257     int i, spec_char, plus_char;
1258     char *p, *q;
1259     char *type;
1260     CONF_VALUE *v;
1261     X509_NAME *subj;
1262
1263     subj = X509_REQ_get_subject_name(req);
1264
1265     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1266         int mval;
1267         v = sk_CONF_VALUE_value(dn_sk, i);
1268         p = q = NULL;
1269         type = v->name;
1270         /*
1271          * Skip past any leading X. X: X, etc to allow for multiple instances
1272          */
1273         for (p = v->name; *p; p++) {
1274 #ifndef CHARSET_EBCDIC
1275             spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1276 #else
1277             spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1278                     || (*p == os_toascii['.']));
1279 #endif
1280             if (spec_char) {
1281                 p++;
1282                 if (*p)
1283                     type = p;
1284                 break;
1285             }
1286         }
1287 #ifndef CHARSET_EBCDIC
1288         plus_char = (*type == '+');
1289 #else
1290         plus_char = (*type == os_toascii['+']);
1291 #endif
1292         if (plus_char) {
1293             type++;
1294             mval = -1;
1295         } else {
1296             mval = 0;
1297         }
1298         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1299                                         (unsigned char *)v->value, -1, -1,
1300                                         mval))
1301             return 0;
1302
1303     }
1304
1305     if (!X509_NAME_entry_count(subj)) {
1306         BIO_printf(bio_err, "error, no objects specified in config file\n");
1307         return 0;
1308     }
1309     if (attribs) {
1310         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1311             v = sk_CONF_VALUE_value(attr_sk, i);
1312             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1313                                            (unsigned char *)v->value, -1))
1314                 return 0;
1315         }
1316     }
1317     return 1;
1318 }
1319
1320 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1321                          char *value, int nid, int n_min, int n_max,
1322                          unsigned long chtype, int mval)
1323 {
1324     int ret = 0;
1325     char buf[1024];
1326
1327     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1328                      "DN value", "DN default");
1329     if ((ret == 0) || (ret == 1))
1330         return ret;
1331     ret = 1;
1332
1333     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1334                                     (unsigned char *)buf, -1, -1, mval))
1335         ret = 0;
1336
1337     return ret;
1338 }
1339
1340 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1341                                 char *value, int nid, int n_min,
1342                                 int n_max, unsigned long chtype)
1343 {
1344     int ret = 0;
1345     char buf[1024];
1346
1347     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1348                      "Attribute value", "Attribute default");
1349     if ((ret == 0) || (ret == 1))
1350         return ret;
1351     ret = 1;
1352
1353     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1354                                    (unsigned char *)buf, -1)) {
1355         BIO_printf(bio_err, "Error adding attribute\n");
1356         ERR_print_errors(bio_err);
1357         ret = 0;
1358     }
1359
1360     return ret;
1361 }
1362
1363
1364 static int build_data(char *text, const char *def,
1365                          char *value, int n_min, int n_max,
1366                          char *buf, const int buf_size,
1367                          const char *desc1, const char *desc2
1368                          )
1369 {
1370     int i;
1371  start:
1372     if (!batch)
1373         BIO_printf(bio_err, "%s [%s]:", text, def);
1374     (void)BIO_flush(bio_err);
1375     if (value != NULL) {
1376         if (!join(buf, buf_size, value, "\n", desc1))
1377             return 0;
1378         BIO_printf(bio_err, "%s\n", value);
1379     } else {
1380         buf[0] = '\0';
1381         if (!batch) {
1382             if (!fgets(buf, buf_size, stdin))
1383                 return 0;
1384         } else {
1385             buf[0] = '\n';
1386             buf[1] = '\0';
1387         }
1388     }
1389
1390     if (buf[0] == '\0')
1391         return 0;
1392     if (buf[0] == '\n') {
1393         if ((def == NULL) || (def[0] == '\0'))
1394             return 1;
1395         if (!join(buf, buf_size, def, "\n", desc2))
1396             return 0;
1397     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1398         return 1;
1399     }
1400
1401     i = strlen(buf);
1402     if (buf[i - 1] != '\n') {
1403         BIO_printf(bio_err, "weird input :-(\n");
1404         return 0;
1405     }
1406     buf[--i] = '\0';
1407 #ifdef CHARSET_EBCDIC
1408     ebcdic2ascii(buf, buf, i);
1409 #endif
1410     if (!req_check_len(i, n_min, n_max)) {
1411         if (batch || value)
1412             return 0;
1413         goto start;
1414     }
1415     return 2;
1416 }
1417
1418 static int req_check_len(int len, int n_min, int n_max)
1419 {
1420     if ((n_min > 0) && (len < n_min)) {
1421         BIO_printf(bio_err,
1422                    "string is too short, it needs to be at least %d bytes long\n",
1423                    n_min);
1424         return 0;
1425     }
1426     if ((n_max >= 0) && (len > n_max)) {
1427         BIO_printf(bio_err,
1428                    "string is too long, it needs to be no more than %d bytes long\n",
1429                    n_max);
1430         return 0;
1431     }
1432     return 1;
1433 }
1434
1435 /* Check if the end of a string matches 'end' */
1436 static int check_end(const char *str, const char *end)
1437 {
1438     size_t elen, slen;
1439     const char *tmp;
1440
1441     elen = strlen(end);
1442     slen = strlen(str);
1443     if (elen > slen)
1444         return 1;
1445     tmp = str + slen - elen;
1446     return strcmp(tmp, end);
1447 }
1448
1449 /*
1450  * Merge the two strings together into the result buffer checking for
1451  * overflow and producing an error message if there is.
1452  */
1453 static int join(char buf[], size_t buf_size, const char *name,
1454                 const char *tail, const char *desc)
1455 {
1456     const size_t name_len = strlen(name), tail_len = strlen(tail);
1457
1458     if (name_len + tail_len + 1 > buf_size) {
1459         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1460         return 0;
1461     }
1462     memcpy(buf, name, name_len);
1463     memcpy(buf + name_len, tail, tail_len + 1);
1464     return 1;
1465 }
1466
1467 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1468                                     int *pkey_type, long *pkeylen,
1469                                     char **palgnam, ENGINE *keygen_engine)
1470 {
1471     EVP_PKEY_CTX *gctx = NULL;
1472     EVP_PKEY *param = NULL;
1473     long keylen = -1;
1474     BIO *pbio = NULL;
1475     const char *paramfile = NULL;
1476
1477     if (gstr == NULL) {
1478         *pkey_type = EVP_PKEY_RSA;
1479         keylen = *pkeylen;
1480     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1481         *pkey_type = EVP_PKEY_RSA;
1482         keylen = atol(gstr);
1483         *pkeylen = keylen;
1484     } else if (strncmp(gstr, "param:", 6) == 0) {
1485         paramfile = gstr + 6;
1486     } else {
1487         const char *p = strchr(gstr, ':');
1488         int len;
1489         ENGINE *tmpeng;
1490         const EVP_PKEY_ASN1_METHOD *ameth;
1491
1492         if (p != NULL)
1493             len = p - gstr;
1494         else
1495             len = strlen(gstr);
1496         /*
1497          * The lookup of a the string will cover all engines so keep a note
1498          * of the implementation.
1499          */
1500
1501         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1502
1503         if (ameth == NULL) {
1504             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1505             return NULL;
1506         }
1507
1508         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1509 #ifndef OPENSSL_NO_ENGINE
1510         finish_engine(tmpeng);
1511 #endif
1512         if (*pkey_type == EVP_PKEY_RSA) {
1513             if (p != NULL) {
1514                 keylen = atol(p + 1);
1515                 *pkeylen = keylen;
1516             } else {
1517                 keylen = *pkeylen;
1518             }
1519         } else if (p != NULL) {
1520             paramfile = p + 1;
1521         }
1522     }
1523
1524     if (paramfile != NULL) {
1525         pbio = BIO_new_file(paramfile, "r");
1526         if (pbio == NULL) {
1527             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1528             return NULL;
1529         }
1530         param = PEM_read_bio_Parameters(pbio, NULL);
1531
1532         if (param == NULL) {
1533             X509 *x;
1534
1535             (void)BIO_reset(pbio);
1536             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1537             if (x != NULL) {
1538                 param = X509_get_pubkey(x);
1539                 X509_free(x);
1540             }
1541         }
1542
1543         BIO_free(pbio);
1544
1545         if (param == NULL) {
1546             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1547             return NULL;
1548         }
1549         if (*pkey_type == -1) {
1550             *pkey_type = EVP_PKEY_id(param);
1551         } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1552             BIO_printf(bio_err, "Key Type does not match parameters\n");
1553             EVP_PKEY_free(param);
1554             return NULL;
1555         }
1556     }
1557
1558     if (palgnam != NULL) {
1559         const EVP_PKEY_ASN1_METHOD *ameth;
1560         ENGINE *tmpeng;
1561         const char *anam;
1562
1563         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1564         if (ameth == NULL) {
1565             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1566             return NULL;
1567         }
1568         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1569         *palgnam = OPENSSL_strdup(anam);
1570 #ifndef OPENSSL_NO_ENGINE
1571         finish_engine(tmpeng);
1572 #endif
1573     }
1574
1575     if (param != NULL) {
1576         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1577         *pkeylen = EVP_PKEY_bits(param);
1578         EVP_PKEY_free(param);
1579     } else {
1580         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1581     }
1582
1583     if (gctx == NULL) {
1584         BIO_puts(bio_err, "Error allocating keygen context\n");
1585         ERR_print_errors(bio_err);
1586         return NULL;
1587     }
1588
1589     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1590         BIO_puts(bio_err, "Error initializing keygen context\n");
1591         ERR_print_errors(bio_err);
1592         EVP_PKEY_CTX_free(gctx);
1593         return NULL;
1594     }
1595 #ifndef OPENSSL_NO_RSA
1596     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1597         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1598             BIO_puts(bio_err, "Error setting RSA keysize\n");
1599             ERR_print_errors(bio_err);
1600             EVP_PKEY_CTX_free(gctx);
1601             return NULL;
1602         }
1603     }
1604 #endif
1605
1606     return gctx;
1607 }
1608
1609 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1610 {
1611     char c = '*';
1612     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1613     int p;
1614     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1615     if (p == 0)
1616         c = '.';
1617     if (p == 1)
1618         c = '+';
1619     if (p == 2)
1620         c = '*';
1621     if (p == 3)
1622         c = '\n';
1623     BIO_write(b, &c, 1);
1624     (void)BIO_flush(b);
1625     return 1;
1626 }
1627
1628 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1629 {
1630     int i;
1631
1632     if (opts == NULL)
1633         return 1;
1634
1635     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1636         char *opt = sk_OPENSSL_STRING_value(opts, i);
1637         if (pkey_ctrl_string(pkctx, opt) <= 0) {
1638             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1639             ERR_print_errors(bio_err);
1640             return 0;
1641         }
1642     }
1643
1644     return 1;
1645 }
1646
1647 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1648 {
1649     int i;
1650
1651     if (opts == NULL)
1652         return 1;
1653
1654     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1655         char *opt = sk_OPENSSL_STRING_value(opts, i);
1656         if (x509_ctrl_string(x, opt) <= 0) {
1657             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1658             ERR_print_errors(bio_err);
1659             return 0;
1660         }
1661     }
1662
1663     return 1;
1664 }
1665
1666 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1667 {
1668     int i;
1669
1670     if (opts == NULL)
1671         return 1;
1672
1673     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1674         char *opt = sk_OPENSSL_STRING_value(opts, i);
1675         if (x509_req_ctrl_string(x, opt) <= 0) {
1676             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1677             ERR_print_errors(bio_err);
1678             return 0;
1679         }
1680     }
1681
1682     return 1;
1683 }
1684
1685 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1686                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1687 {
1688     EVP_PKEY_CTX *pkctx = NULL;
1689     int def_nid;
1690
1691     if (ctx == NULL)
1692         return 0;
1693     /*
1694      * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1695      * for this algorithm.
1696      */
1697     if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1698             && def_nid == NID_undef) {
1699         /* The signing algorithm requires there to be no digest */
1700         md = NULL;
1701     }
1702     return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1703         && do_pkey_ctx_init(pkctx, sigopts);
1704 }
1705
1706 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1707                  STACK_OF(OPENSSL_STRING) *sigopts)
1708 {
1709     int rv = 0;
1710     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1711
1712     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1713         rv = (X509_sign_ctx(x, mctx) > 0);
1714     EVP_MD_CTX_free(mctx);
1715     return rv;
1716 }
1717
1718 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1719                      STACK_OF(OPENSSL_STRING) *sigopts)
1720 {
1721     int rv = 0;
1722     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1723
1724     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1725         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1726     EVP_MD_CTX_free(mctx);
1727     return rv;
1728 }
1729
1730 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1731 {
1732     int rv = 0;
1733
1734     if (do_x509_init(x, vfyopts) > 0)
1735         rv = (X509_verify(x, pkey) > 0);
1736     return rv;
1737 }
1738
1739 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1740                        STACK_OF(OPENSSL_STRING) *vfyopts)
1741 {
1742     int rv = 0;
1743
1744     if (do_x509_req_init(x, vfyopts) > 0)
1745         rv = (X509_REQ_verify(x, pkey) > 0);
1746     return rv;
1747 }
1748
1749 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1750                      STACK_OF(OPENSSL_STRING) *sigopts)
1751 {
1752     int rv = 0;
1753     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1754
1755     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1756         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1757     EVP_MD_CTX_free(mctx);
1758     return rv;
1759 }