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