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