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