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