source: rtems-libbsd/freebsd/crypto/openssl/apps/req.c @ 0fecf49

5
Last change on this file since 0fecf49 was 0fecf49, checked in by Christian Mauderer <christian.mauderer@…>, on 03/26/19 at 09:19:22

bin/openssl: Import from FreeBSD.

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