VirtualBox

source: vbox/trunk/src/libs/openssl-3.0.2/apps/req.c@ 94403

最後變更 在這個檔案從94403是 94082,由 vboxsync 提交於 3 年 前

libs/openssl-3.0.1: started applying and adjusting our OpenSSL changes to 3.0.1. bugref:10128

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette