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