]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/req.c
Check return value after loading config file
[thirdparty/openssl.git] / apps / req.c
1 /*
2 * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (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 #ifndef OPENSSL_NO_RSA
29 # include <openssl/rsa.h>
30 #endif
31 #ifndef OPENSSL_NO_DSA
32 # include <openssl/dsa.h>
33 #endif
34
35 #define SECTION "req"
36
37 #define BITS "default_bits"
38 #define KEYFILE "default_keyfile"
39 #define PROMPT "prompt"
40 #define DISTINGUISHED_NAME "distinguished_name"
41 #define ATTRIBUTES "attributes"
42 #define V3_EXTENSIONS "x509_extensions"
43 #define REQ_EXTENSIONS "req_extensions"
44 #define STRING_MASK "string_mask"
45 #define UTF8_IN "utf8"
46
47 #define DEFAULT_KEY_LENGTH 2048
48 #define MIN_KEY_LENGTH 512
49
50 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
51 int attribs, unsigned long chtype);
52 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
53 int multirdn);
54 static int prompt_info(X509_REQ *req,
55 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
56 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
57 int attribs, unsigned long chtype);
58 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
59 STACK_OF(CONF_VALUE) *attr, int attribs,
60 unsigned long chtype);
61 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
62 char *value, int nid, int n_min, int n_max,
63 unsigned long chtype);
64 static int add_DN_object(X509_NAME *n, char *text, const char *def,
65 char *value, int nid, int n_min, int n_max,
66 unsigned long chtype, int mval);
67 static int genpkey_cb(EVP_PKEY_CTX *ctx);
68 static int build_data(char *text, const char *def,
69 char *value, int n_min, int n_max,
70 char *buf, const int buf_size,
71 const char *desc1, const char *desc2
72 );
73 static int req_check_len(int len, int n_min, int n_max);
74 static int check_end(const char *str, const char *end);
75 static int join(char buf[], size_t buf_size, const char *name,
76 const char *tail, const char *desc);
77 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
78 int *pkey_type, long *pkeylen,
79 char **palgnam, ENGINE *keygen_engine);
80 static CONF *req_conf = NULL;
81 static CONF *addext_conf = NULL;
82 static int batch = 0;
83
84 typedef enum OPTION_choice {
85 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
86 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
87 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
88 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
89 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
90 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
91 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
92 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
93 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
94 OPT_R_ENUM
95 } OPTION_CHOICE;
96
97 const OPTIONS req_options[] = {
98 {"help", OPT_HELP, '-', "Display this summary"},
99 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
100 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
101 {"in", OPT_IN, '<', "Input file"},
102 {"out", OPT_OUT, '>', "Output file"},
103 {"key", OPT_KEY, 's', "Private key to use"},
104 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
105 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
106 {"new", OPT_NEW, '-', "New request"},
107 {"config", OPT_CONFIG, '<', "Request template file"},
108 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
109 {"passin", OPT_PASSIN, 's', "Private key password source"},
110 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
111 OPT_R_OPTIONS,
112 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
113 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
114 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
115 {"batch", OPT_BATCH, '-',
116 "Do not ask anything during request generation"},
117 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
118 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
119 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
120 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
121 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
122 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
123 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
124 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
125 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
126 {"text", OPT_TEXT, '-', "Text form of request"},
127 {"x509", OPT_X509, '-',
128 "Output a x509 structure instead of a cert request"},
129 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
130 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
131 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
132 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
133 "Enable support for multivalued RDNs"},
134 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
135 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
136 {"addext", OPT_ADDEXT, 's',
137 "Additional cert extension key=value pair (may be given more than once)"},
138 {"extensions", OPT_EXTENSIONS, 's',
139 "Cert extension section (override value in config file)"},
140 {"reqexts", OPT_REQEXTS, 's',
141 "Request extension section (override value in config file)"},
142 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
143 {"", OPT_MD, '-', "Any supported digest"},
144 #ifndef OPENSSL_NO_ENGINE
145 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
146 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
147 "Specify engine to be used for key generation operations"},
148 #endif
149 {NULL}
150 };
151
152
153 /*
154 * An LHASH of strings, where each string is an extension name.
155 */
156 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
157 {
158 return OPENSSL_LH_strhash((const char *)a);
159 }
160
161 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
162 {
163 return strcmp((const char *)a, (const char *)b);
164 }
165
166 static void exts_cleanup(OPENSSL_STRING *x)
167 {
168 OPENSSL_free((char *)x);
169 }
170
171 /*
172 * Is the |kv| key already duplicated? This is remarkably tricky to get
173 * right. Return 0 if unique, -1 on runtime error; 1 if found or a syntax
174 * error.
175 */
176 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
177 {
178 char *p;
179 size_t off;
180
181 /* Check syntax. */
182 /* Skip leading whitespace, make a copy. */
183 while (*kv && isspace(*kv))
184 if (*++kv == '\0')
185 return 1;
186 if ((p = strchr(kv, '=')) == NULL)
187 return 1;
188 off = p - kv;
189 if ((kv = OPENSSL_strdup(kv)) == NULL)
190 return -1;
191
192 /* Skip trailing space before the equal sign. */
193 for (p = kv + off; p > kv; --p)
194 if (!isspace(p[-1]))
195 break;
196 if (p == kv) {
197 OPENSSL_free(kv);
198 return 1;
199 }
200 *p = '\0';
201
202 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
203 if ((p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv))
204 != NULL || lh_OPENSSL_STRING_error(addexts)) {
205 OPENSSL_free(p != NULL ? p : kv);
206 return -1;
207 }
208
209 return 0;
210 }
211
212 int req_main(int argc, char **argv)
213 {
214 ASN1_INTEGER *serial = NULL;
215 BIO *in = NULL, *out = NULL;
216 ENGINE *e = NULL, *gen_eng = NULL;
217 EVP_PKEY *pkey = NULL;
218 EVP_PKEY_CTX *genctx = NULL;
219 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
220 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
221 X509 *x509ss = NULL;
222 X509_REQ *req = NULL;
223 const EVP_CIPHER *cipher = NULL;
224 const EVP_MD *md_alg = NULL, *digest = NULL;
225 BIO *addext_bio = NULL;
226 char *extensions = NULL, *infile = NULL;
227 char *outfile = NULL, *keyfile = NULL;
228 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
229 char *passin = NULL, *passout = NULL;
230 char *nofree_passin = NULL, *nofree_passout = NULL;
231 char *req_exts = NULL, *subj = NULL;
232 char *template = default_config_file, *keyout = NULL;
233 const char *keyalg = NULL;
234 OPTION_CHOICE o;
235 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
236 int pkey_type = -1, private = 0;
237 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
238 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
239 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
240 long newkey = -1;
241 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
242
243 #ifndef OPENSSL_NO_DES
244 cipher = EVP_des_ede3_cbc();
245 #endif
246
247 prog = opt_init(argc, argv, req_options);
248 while ((o = opt_next()) != OPT_EOF) {
249 switch (o) {
250 case OPT_EOF:
251 case OPT_ERR:
252 opthelp:
253 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
254 goto end;
255 case OPT_HELP:
256 opt_help(req_options);
257 ret = 0;
258 goto end;
259 case OPT_INFORM:
260 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
261 goto opthelp;
262 break;
263 case OPT_OUTFORM:
264 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
265 goto opthelp;
266 break;
267 case OPT_ENGINE:
268 e = setup_engine(opt_arg(), 0);
269 break;
270 case OPT_KEYGEN_ENGINE:
271 #ifndef OPENSSL_NO_ENGINE
272 gen_eng = ENGINE_by_id(opt_arg());
273 if (gen_eng == NULL) {
274 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
275 goto opthelp;
276 }
277 #endif
278 break;
279 case OPT_KEY:
280 keyfile = opt_arg();
281 break;
282 case OPT_PUBKEY:
283 pubkey = 1;
284 break;
285 case OPT_NEW:
286 newreq = 1;
287 break;
288 case OPT_CONFIG:
289 template = opt_arg();
290 break;
291 case OPT_KEYFORM:
292 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
293 goto opthelp;
294 break;
295 case OPT_IN:
296 infile = opt_arg();
297 break;
298 case OPT_OUT:
299 outfile = opt_arg();
300 break;
301 case OPT_KEYOUT:
302 keyout = opt_arg();
303 break;
304 case OPT_PASSIN:
305 passargin = opt_arg();
306 break;
307 case OPT_PASSOUT:
308 passargout = opt_arg();
309 break;
310 case OPT_R_CASES:
311 if (!opt_rand(o))
312 goto end;
313 break;
314 case OPT_NEWKEY:
315 keyalg = opt_arg();
316 newreq = 1;
317 break;
318 case OPT_PKEYOPT:
319 if (!pkeyopts)
320 pkeyopts = sk_OPENSSL_STRING_new_null();
321 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
322 goto opthelp;
323 break;
324 case OPT_SIGOPT:
325 if (!sigopts)
326 sigopts = sk_OPENSSL_STRING_new_null();
327 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
328 goto opthelp;
329 break;
330 case OPT_BATCH:
331 batch = 1;
332 break;
333 case OPT_NEWHDR:
334 newhdr = 1;
335 break;
336 case OPT_MODULUS:
337 modulus = 1;
338 break;
339 case OPT_VERIFY:
340 verify = 1;
341 break;
342 case OPT_NODES:
343 nodes = 1;
344 break;
345 case OPT_NOOUT:
346 noout = 1;
347 break;
348 case OPT_VERBOSE:
349 verbose = 1;
350 break;
351 case OPT_UTF8:
352 chtype = MBSTRING_UTF8;
353 break;
354 case OPT_NAMEOPT:
355 if (!set_nameopt(opt_arg()))
356 goto opthelp;
357 break;
358 case OPT_REQOPT:
359 if (!set_cert_ex(&reqflag, opt_arg()))
360 goto opthelp;
361 break;
362 case OPT_TEXT:
363 text = 1;
364 break;
365 case OPT_X509:
366 x509 = 1;
367 break;
368 case OPT_DAYS:
369 days = atoi(opt_arg());
370 break;
371 case OPT_SET_SERIAL:
372 if (serial != NULL) {
373 BIO_printf(bio_err, "Serial number supplied twice\n");
374 goto opthelp;
375 }
376 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
377 if (serial == NULL)
378 goto opthelp;
379 break;
380 case OPT_SUBJECT:
381 subject = 1;
382 break;
383 case OPT_SUBJ:
384 subj = opt_arg();
385 break;
386 case OPT_MULTIVALUE_RDN:
387 multirdn = 1;
388 break;
389 case OPT_ADDEXT:
390 p = opt_arg();
391 if (addexts == NULL) {
392 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
393 addext_bio = BIO_new(BIO_s_mem());
394 if (addexts == NULL || addext_bio == NULL)
395 goto end;
396 }
397 i = duplicated(addexts, p);
398 if (i == 1)
399 goto opthelp;
400 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
401 goto end;
402 break;
403 case OPT_EXTENSIONS:
404 extensions = opt_arg();
405 break;
406 case OPT_REQEXTS:
407 req_exts = opt_arg();
408 break;
409 case OPT_PRECERT:
410 newreq = precert = 1;
411 break;
412 case OPT_MD:
413 if (!opt_md(opt_unknown(), &md_alg))
414 goto opthelp;
415 digest = md_alg;
416 break;
417 }
418 }
419 argc = opt_num_rest();
420 if (argc != 0)
421 goto opthelp;
422
423 if (days && !x509)
424 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
425 if (x509 && infile == NULL)
426 newreq = 1;
427
428 /* TODO: simplify this as pkey is still always NULL here */
429 private = newreq && (pkey == NULL) ? 1 : 0;
430
431 if (!app_passwd(passargin, passargout, &passin, &passout)) {
432 BIO_printf(bio_err, "Error getting passwords\n");
433 goto end;
434 }
435
436 if (verbose)
437 BIO_printf(bio_err, "Using configuration from %s\n", template);
438 if ((req_conf = app_load_config(template)) == NULL)
439 goto end;
440 if (addext_bio) {
441 if (verbose)
442 BIO_printf(bio_err,
443 "Using additional configuration from command line\n");
444 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
445 goto end;
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 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
887 else
888 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
889
890 if (ret == 0) {
891 if (x509)
892 BIO_printf(bio_err, "Error printing certificate\n");
893 else
894 BIO_printf(bio_err, "Error printing certificate request\n");
895
896 ERR_print_errors(bio_err);
897 goto end;
898 }
899 }
900
901 if (subject) {
902 if (x509)
903 print_name(out, "subject=", X509_get_subject_name(x509ss),
904 get_nameopt());
905 else
906 print_name(out, "subject=", X509_REQ_get_subject_name(req),
907 get_nameopt());
908 }
909
910 if (modulus) {
911 EVP_PKEY *tpubkey;
912
913 if (x509)
914 tpubkey = X509_get0_pubkey(x509ss);
915 else
916 tpubkey = X509_REQ_get0_pubkey(req);
917 if (tpubkey == NULL) {
918 fprintf(stdout, "Modulus=unavailable\n");
919 goto end;
920 }
921 fprintf(stdout, "Modulus=");
922 #ifndef OPENSSL_NO_RSA
923 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
924 const BIGNUM *n;
925 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
926 BN_print(out, n);
927 } else
928 #endif
929 fprintf(stdout, "Wrong Algorithm type");
930 fprintf(stdout, "\n");
931 }
932
933 if (!noout && !x509) {
934 if (outformat == FORMAT_ASN1)
935 i = i2d_X509_REQ_bio(out, req);
936 else if (newhdr)
937 i = PEM_write_bio_X509_REQ_NEW(out, req);
938 else
939 i = PEM_write_bio_X509_REQ(out, req);
940 if (!i) {
941 BIO_printf(bio_err, "unable to write X509 request\n");
942 goto end;
943 }
944 }
945 if (!noout && x509 && (x509ss != NULL)) {
946 if (outformat == FORMAT_ASN1)
947 i = i2d_X509_bio(out, x509ss);
948 else
949 i = PEM_write_bio_X509(out, x509ss);
950 if (!i) {
951 BIO_printf(bio_err, "unable to write X509 certificate\n");
952 goto end;
953 }
954 }
955 ret = 0;
956 end:
957 if (ret) {
958 ERR_print_errors(bio_err);
959 }
960 NCONF_free(req_conf);
961 NCONF_free(addext_conf);
962 BIO_free(addext_bio);
963 BIO_free(in);
964 BIO_free_all(out);
965 EVP_PKEY_free(pkey);
966 EVP_PKEY_CTX_free(genctx);
967 sk_OPENSSL_STRING_free(pkeyopts);
968 sk_OPENSSL_STRING_free(sigopts);
969 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
970 lh_OPENSSL_STRING_free(addexts);
971 #ifndef OPENSSL_NO_ENGINE
972 ENGINE_free(gen_eng);
973 #endif
974 OPENSSL_free(keyalgstr);
975 X509_REQ_free(req);
976 X509_free(x509ss);
977 ASN1_INTEGER_free(serial);
978 release_engine(e);
979 if (passin != nofree_passin)
980 OPENSSL_free(passin);
981 if (passout != nofree_passout)
982 OPENSSL_free(passout);
983 return ret;
984 }
985
986 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
987 int attribs, unsigned long chtype)
988 {
989 int ret = 0, i;
990 char no_prompt = 0;
991 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
992 char *tmp, *dn_sect, *attr_sect;
993
994 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
995 if (tmp == NULL)
996 ERR_clear_error();
997 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
998 no_prompt = 1;
999
1000 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
1001 if (dn_sect == NULL) {
1002 BIO_printf(bio_err, "unable to find '%s' in config\n",
1003 DISTINGUISHED_NAME);
1004 goto err;
1005 }
1006 dn_sk = NCONF_get_section(req_conf, dn_sect);
1007 if (dn_sk == NULL) {
1008 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1009 goto err;
1010 }
1011
1012 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
1013 if (attr_sect == NULL) {
1014 ERR_clear_error();
1015 attr_sk = NULL;
1016 } else {
1017 attr_sk = NCONF_get_section(req_conf, attr_sect);
1018 if (attr_sk == NULL) {
1019 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1020 goto err;
1021 }
1022 }
1023
1024 /* setup version number */
1025 if (!X509_REQ_set_version(req, 0L))
1026 goto err; /* version 1 */
1027
1028 if (subj)
1029 i = build_subject(req, subj, chtype, multirdn);
1030 else if (no_prompt)
1031 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1032 else
1033 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1034 chtype);
1035 if (!i)
1036 goto err;
1037
1038 if (!X509_REQ_set_pubkey(req, pkey))
1039 goto err;
1040
1041 ret = 1;
1042 err:
1043 return ret;
1044 }
1045
1046 /*
1047 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1048 * where characters may be escaped by \
1049 */
1050 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1051 int multirdn)
1052 {
1053 X509_NAME *n;
1054
1055 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1056 return 0;
1057
1058 if (!X509_REQ_set_subject_name(req, n)) {
1059 X509_NAME_free(n);
1060 return 0;
1061 }
1062 X509_NAME_free(n);
1063 return 1;
1064 }
1065
1066 static int prompt_info(X509_REQ *req,
1067 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1068 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1069 int attribs, unsigned long chtype)
1070 {
1071 int i;
1072 char *p, *q;
1073 char buf[100];
1074 int nid, mval;
1075 long n_min, n_max;
1076 char *type, *value;
1077 const char *def;
1078 CONF_VALUE *v;
1079 X509_NAME *subj;
1080 subj = X509_REQ_get_subject_name(req);
1081
1082 if (!batch) {
1083 BIO_printf(bio_err,
1084 "You are about to be asked to enter information that will be incorporated\n");
1085 BIO_printf(bio_err, "into your certificate request.\n");
1086 BIO_printf(bio_err,
1087 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1088 BIO_printf(bio_err,
1089 "There are quite a few fields but you can leave some blank\n");
1090 BIO_printf(bio_err,
1091 "For some fields there will be a default value,\n");
1092 BIO_printf(bio_err,
1093 "If you enter '.', the field will be left blank.\n");
1094 BIO_printf(bio_err, "-----\n");
1095 }
1096
1097 if (sk_CONF_VALUE_num(dn_sk)) {
1098 i = -1;
1099 start:
1100 for ( ; ; ) {
1101 i++;
1102 if (sk_CONF_VALUE_num(dn_sk) <= i)
1103 break;
1104
1105 v = sk_CONF_VALUE_value(dn_sk, i);
1106 p = q = NULL;
1107 type = v->name;
1108 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1109 !check_end(type, "_default") || !check_end(type, "_value"))
1110 continue;
1111 /*
1112 * Skip past any leading X. X: X, etc to allow for multiple
1113 * instances
1114 */
1115 for (p = v->name; *p; p++)
1116 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1117 p++;
1118 if (*p)
1119 type = p;
1120 break;
1121 }
1122 if (*type == '+') {
1123 mval = -1;
1124 type++;
1125 } else {
1126 mval = 0;
1127 }
1128 /* If OBJ not recognised ignore it */
1129 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1130 goto start;
1131 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1132 return 0;
1133 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1134 ERR_clear_error();
1135 def = "";
1136 }
1137
1138 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1139 return 0;
1140 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1141 ERR_clear_error();
1142 value = NULL;
1143 }
1144
1145 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1146 return 0;
1147 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1148 ERR_clear_error();
1149 n_min = -1;
1150 }
1151
1152
1153 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1154 return 0;
1155 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1156 ERR_clear_error();
1157 n_max = -1;
1158 }
1159
1160 if (!add_DN_object(subj, v->value, def, value, nid,
1161 n_min, n_max, chtype, mval))
1162 return 0;
1163 }
1164 if (X509_NAME_entry_count(subj) == 0) {
1165 BIO_printf(bio_err,
1166 "error, no objects specified in config file\n");
1167 return 0;
1168 }
1169
1170 if (attribs) {
1171 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1172 && (!batch)) {
1173 BIO_printf(bio_err,
1174 "\nPlease enter the following 'extra' attributes\n");
1175 BIO_printf(bio_err,
1176 "to be sent with your certificate request\n");
1177 }
1178
1179 i = -1;
1180 start2:
1181 for ( ; ; ) {
1182 i++;
1183 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1184 break;
1185
1186 v = sk_CONF_VALUE_value(attr_sk, i);
1187 type = v->name;
1188 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1189 goto start2;
1190
1191 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1192 return 0;
1193 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1194 == NULL) {
1195 ERR_clear_error();
1196 def = "";
1197 }
1198
1199 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1200 return 0;
1201 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1202 == NULL) {
1203 ERR_clear_error();
1204 value = NULL;
1205 }
1206
1207 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1208 return 0;
1209 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1210 ERR_clear_error();
1211 n_min = -1;
1212 }
1213
1214 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1215 return 0;
1216 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1217 ERR_clear_error();
1218 n_max = -1;
1219 }
1220
1221 if (!add_attribute_object(req,
1222 v->value, def, value, nid, n_min,
1223 n_max, chtype))
1224 return 0;
1225 }
1226 }
1227 } else {
1228 BIO_printf(bio_err, "No template, please set one up.\n");
1229 return 0;
1230 }
1231
1232 return 1;
1233
1234 }
1235
1236 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1237 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1238 unsigned long chtype)
1239 {
1240 int i, spec_char, plus_char;
1241 char *p, *q;
1242 char *type;
1243 CONF_VALUE *v;
1244 X509_NAME *subj;
1245
1246 subj = X509_REQ_get_subject_name(req);
1247
1248 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1249 int mval;
1250 v = sk_CONF_VALUE_value(dn_sk, i);
1251 p = q = NULL;
1252 type = v->name;
1253 /*
1254 * Skip past any leading X. X: X, etc to allow for multiple instances
1255 */
1256 for (p = v->name; *p; p++) {
1257 #ifndef CHARSET_EBCDIC
1258 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1259 #else
1260 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1261 || (*p == os_toascii['.']));
1262 #endif
1263 if (spec_char) {
1264 p++;
1265 if (*p)
1266 type = p;
1267 break;
1268 }
1269 }
1270 #ifndef CHARSET_EBCDIC
1271 plus_char = (*type == '+');
1272 #else
1273 plus_char = (*type == os_toascii['+']);
1274 #endif
1275 if (plus_char) {
1276 type++;
1277 mval = -1;
1278 } else {
1279 mval = 0;
1280 }
1281 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1282 (unsigned char *)v->value, -1, -1,
1283 mval))
1284 return 0;
1285
1286 }
1287
1288 if (!X509_NAME_entry_count(subj)) {
1289 BIO_printf(bio_err, "error, no objects specified in config file\n");
1290 return 0;
1291 }
1292 if (attribs) {
1293 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1294 v = sk_CONF_VALUE_value(attr_sk, i);
1295 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1296 (unsigned char *)v->value, -1))
1297 return 0;
1298 }
1299 }
1300 return 1;
1301 }
1302
1303 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1304 char *value, int nid, int n_min, int n_max,
1305 unsigned long chtype, int mval)
1306 {
1307 int ret = 0;
1308 char buf[1024];
1309
1310 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1311 "DN value", "DN default");
1312 if ((ret == 0) || (ret == 1))
1313 return ret;
1314 ret = 1;
1315
1316 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1317 (unsigned char *)buf, -1, -1, mval))
1318 ret = 0;
1319
1320 return ret;
1321 }
1322
1323 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1324 char *value, int nid, int n_min,
1325 int n_max, unsigned long chtype)
1326 {
1327 int ret = 0;
1328 char buf[1024];
1329
1330 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1331 "Attribute value", "Attribute default");
1332 if ((ret == 0) || (ret == 1))
1333 return ret;
1334 ret = 1;
1335
1336 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1337 (unsigned char *)buf, -1)) {
1338 BIO_printf(bio_err, "Error adding attribute\n");
1339 ERR_print_errors(bio_err);
1340 ret = 0;
1341 }
1342
1343 return ret;
1344 }
1345
1346
1347 static int build_data(char *text, const char *def,
1348 char *value, int n_min, int n_max,
1349 char *buf, const int buf_size,
1350 const char *desc1, const char *desc2
1351 )
1352 {
1353 int i;
1354 start:
1355 if (!batch)
1356 BIO_printf(bio_err, "%s [%s]:", text, def);
1357 (void)BIO_flush(bio_err);
1358 if (value != NULL) {
1359 if (!join(buf, buf_size, value, "\n", desc1))
1360 return 0;
1361 BIO_printf(bio_err, "%s\n", value);
1362 } else {
1363 buf[0] = '\0';
1364 if (!batch) {
1365 if (!fgets(buf, buf_size, stdin))
1366 return 0;
1367 } else {
1368 buf[0] = '\n';
1369 buf[1] = '\0';
1370 }
1371 }
1372
1373 if (buf[0] == '\0')
1374 return 0;
1375 if (buf[0] == '\n') {
1376 if ((def == NULL) || (def[0] == '\0'))
1377 return 1;
1378 if (!join(buf, buf_size, def, "\n", desc2))
1379 return 0;
1380 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1381 return 1;
1382 }
1383
1384 i = strlen(buf);
1385 if (buf[i - 1] != '\n') {
1386 BIO_printf(bio_err, "weird input :-(\n");
1387 return 0;
1388 }
1389 buf[--i] = '\0';
1390 #ifdef CHARSET_EBCDIC
1391 ebcdic2ascii(buf, buf, i);
1392 #endif
1393 if (!req_check_len(i, n_min, n_max)) {
1394 if (batch || value)
1395 return 0;
1396 goto start;
1397 }
1398 return 2;
1399 }
1400
1401 static int req_check_len(int len, int n_min, int n_max)
1402 {
1403 if ((n_min > 0) && (len < n_min)) {
1404 BIO_printf(bio_err,
1405 "string is too short, it needs to be at least %d bytes long\n",
1406 n_min);
1407 return 0;
1408 }
1409 if ((n_max >= 0) && (len > n_max)) {
1410 BIO_printf(bio_err,
1411 "string is too long, it needs to be no more than %d bytes long\n",
1412 n_max);
1413 return 0;
1414 }
1415 return 1;
1416 }
1417
1418 /* Check if the end of a string matches 'end' */
1419 static int check_end(const char *str, const char *end)
1420 {
1421 size_t elen, slen;
1422 const char *tmp;
1423
1424 elen = strlen(end);
1425 slen = strlen(str);
1426 if (elen > slen)
1427 return 1;
1428 tmp = str + slen - elen;
1429 return strcmp(tmp, end);
1430 }
1431
1432 /*
1433 * Merge the two strings together into the result buffer checking for
1434 * overflow and producing an error message if there is.
1435 */
1436 static int join(char buf[], size_t buf_size, const char *name,
1437 const char *tail, const char *desc)
1438 {
1439 const size_t name_len = strlen(name), tail_len = strlen(tail);
1440
1441 if (name_len + tail_len + 1 > buf_size) {
1442 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1443 return 0;
1444 }
1445 memcpy(buf, name, name_len);
1446 memcpy(buf + name_len, tail, tail_len + 1);
1447 return 1;
1448 }
1449
1450 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1451 int *pkey_type, long *pkeylen,
1452 char **palgnam, ENGINE *keygen_engine)
1453 {
1454 EVP_PKEY_CTX *gctx = NULL;
1455 EVP_PKEY *param = NULL;
1456 long keylen = -1;
1457 BIO *pbio = NULL;
1458 const char *paramfile = NULL;
1459
1460 if (gstr == NULL) {
1461 *pkey_type = EVP_PKEY_RSA;
1462 keylen = *pkeylen;
1463 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1464 *pkey_type = EVP_PKEY_RSA;
1465 keylen = atol(gstr);
1466 *pkeylen = keylen;
1467 } else if (strncmp(gstr, "param:", 6) == 0) {
1468 paramfile = gstr + 6;
1469 } else {
1470 const char *p = strchr(gstr, ':');
1471 int len;
1472 ENGINE *tmpeng;
1473 const EVP_PKEY_ASN1_METHOD *ameth;
1474
1475 if (p != NULL)
1476 len = p - gstr;
1477 else
1478 len = strlen(gstr);
1479 /*
1480 * The lookup of a the string will cover all engines so keep a note
1481 * of the implementation.
1482 */
1483
1484 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1485
1486 if (ameth == NULL) {
1487 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1488 return NULL;
1489 }
1490
1491 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1492 #ifndef OPENSSL_NO_ENGINE
1493 ENGINE_finish(tmpeng);
1494 #endif
1495 if (*pkey_type == EVP_PKEY_RSA) {
1496 if (p != NULL) {
1497 keylen = atol(p + 1);
1498 *pkeylen = keylen;
1499 } else {
1500 keylen = *pkeylen;
1501 }
1502 } else if (p != NULL) {
1503 paramfile = p + 1;
1504 }
1505 }
1506
1507 if (paramfile != NULL) {
1508 pbio = BIO_new_file(paramfile, "r");
1509 if (pbio == NULL) {
1510 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1511 return NULL;
1512 }
1513 param = PEM_read_bio_Parameters(pbio, NULL);
1514
1515 if (param == NULL) {
1516 X509 *x;
1517
1518 (void)BIO_reset(pbio);
1519 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1520 if (x != NULL) {
1521 param = X509_get_pubkey(x);
1522 X509_free(x);
1523 }
1524 }
1525
1526 BIO_free(pbio);
1527
1528 if (param == NULL) {
1529 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1530 return NULL;
1531 }
1532 if (*pkey_type == -1) {
1533 *pkey_type = EVP_PKEY_id(param);
1534 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1535 BIO_printf(bio_err, "Key Type does not match parameters\n");
1536 EVP_PKEY_free(param);
1537 return NULL;
1538 }
1539 }
1540
1541 if (palgnam != NULL) {
1542 const EVP_PKEY_ASN1_METHOD *ameth;
1543 ENGINE *tmpeng;
1544 const char *anam;
1545
1546 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1547 if (ameth == NULL) {
1548 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1549 return NULL;
1550 }
1551 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1552 *palgnam = OPENSSL_strdup(anam);
1553 #ifndef OPENSSL_NO_ENGINE
1554 ENGINE_finish(tmpeng);
1555 #endif
1556 }
1557
1558 if (param != NULL) {
1559 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1560 *pkeylen = EVP_PKEY_bits(param);
1561 EVP_PKEY_free(param);
1562 } else {
1563 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1564 }
1565
1566 if (gctx == NULL) {
1567 BIO_puts(bio_err, "Error allocating keygen context\n");
1568 ERR_print_errors(bio_err);
1569 return NULL;
1570 }
1571
1572 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1573 BIO_puts(bio_err, "Error initializing keygen context\n");
1574 ERR_print_errors(bio_err);
1575 EVP_PKEY_CTX_free(gctx);
1576 return NULL;
1577 }
1578 #ifndef OPENSSL_NO_RSA
1579 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1580 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1581 BIO_puts(bio_err, "Error setting RSA keysize\n");
1582 ERR_print_errors(bio_err);
1583 EVP_PKEY_CTX_free(gctx);
1584 return NULL;
1585 }
1586 }
1587 #endif
1588
1589 return gctx;
1590 }
1591
1592 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1593 {
1594 char c = '*';
1595 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1596 int p;
1597 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1598 if (p == 0)
1599 c = '.';
1600 if (p == 1)
1601 c = '+';
1602 if (p == 2)
1603 c = '*';
1604 if (p == 3)
1605 c = '\n';
1606 BIO_write(b, &c, 1);
1607 (void)BIO_flush(b);
1608 return 1;
1609 }
1610
1611 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1612 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1613 {
1614 EVP_PKEY_CTX *pkctx = NULL;
1615 int i, def_nid;
1616
1617 if (ctx == NULL)
1618 return 0;
1619 /*
1620 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1621 * for this algorithm.
1622 */
1623 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1624 && def_nid == NID_undef) {
1625 /* The signing algorithm requires there to be no digest */
1626 md = NULL;
1627 }
1628 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1629 return 0;
1630 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1631 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1632 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1633 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1634 ERR_print_errors(bio_err);
1635 return 0;
1636 }
1637 }
1638 return 1;
1639 }
1640
1641 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1642 STACK_OF(OPENSSL_STRING) *sigopts)
1643 {
1644 int rv;
1645 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1646
1647 rv = do_sign_init(mctx, pkey, md, sigopts);
1648 if (rv > 0)
1649 rv = X509_sign_ctx(x, mctx);
1650 EVP_MD_CTX_free(mctx);
1651 return rv > 0 ? 1 : 0;
1652 }
1653
1654 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1655 STACK_OF(OPENSSL_STRING) *sigopts)
1656 {
1657 int rv;
1658 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1659 rv = do_sign_init(mctx, pkey, md, sigopts);
1660 if (rv > 0)
1661 rv = X509_REQ_sign_ctx(x, mctx);
1662 EVP_MD_CTX_free(mctx);
1663 return rv > 0 ? 1 : 0;
1664 }
1665
1666 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1667 STACK_OF(OPENSSL_STRING) *sigopts)
1668 {
1669 int rv;
1670 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1671 rv = do_sign_init(mctx, pkey, md, sigopts);
1672 if (rv > 0)
1673 rv = X509_CRL_sign_ctx(x, mctx);
1674 EVP_MD_CTX_free(mctx);
1675 return rv > 0 ? 1 : 0;
1676 }