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