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