VirtualBox

source: vbox/trunk/src/libs/openssl-3.4.1/apps/req.c@ 109302

Last change on this file since 109302 was 109052, checked in by vboxsync, 4 weeks ago

openssl-3.4.1: Applied our changes, regenerated files, added missing files and functions. This time with a three way merge. ​bugref:10890

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

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