]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/lib/apps.c
Add/harmonize multi-valued RDN support and doc of ca, cmp, req, storeutl, and x509...
[thirdparty/openssl.git] / apps / lib / apps.c
1 /*
2 * Copyright 1995-2020 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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
14 /*
15 * On VMS, you need to define this to get the declaration of fileno(). The
16 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
17 */
18 # define _POSIX_C_SOURCE 2
19 #endif
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #ifndef OPENSSL_NO_POSIX_IO
26 # include <sys/stat.h>
27 # include <fcntl.h>
28 #endif
29 #include <ctype.h>
30 #include <errno.h>
31 #include <openssl/err.h>
32 #include <openssl/x509.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/pem.h>
35 #include <openssl/store.h>
36 #include <openssl/pkcs12.h>
37 #include <openssl/ui.h>
38 #include <openssl/safestack.h>
39 #ifndef OPENSSL_NO_ENGINE
40 # include <openssl/engine.h>
41 #endif
42 #ifndef OPENSSL_NO_RSA
43 # include <openssl/rsa.h>
44 #endif
45 #include <openssl/bn.h>
46 #include <openssl/ssl.h>
47 #include "apps.h"
48
49 #ifdef _WIN32
50 static int WIN32_rename(const char *from, const char *to);
51 # define rename(from,to) WIN32_rename((from),(to))
52 #endif
53
54 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
55 # include <conio.h>
56 #endif
57
58 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
59 # define _kbhit kbhit
60 #endif
61
62 #define PASS_SOURCE_SIZE_MAX 4
63
64 DEFINE_STACK_OF(CONF)
65 DEFINE_STACK_OF(CONF_VALUE)
66 DEFINE_STACK_OF(X509)
67 DEFINE_STACK_OF(X509_CRL)
68 DEFINE_STACK_OF(X509_INFO)
69 DEFINE_STACK_OF(X509_EXTENSION)
70 DEFINE_STACK_OF(X509_POLICY_NODE)
71 DEFINE_STACK_OF(GENERAL_NAME)
72 DEFINE_STACK_OF(DIST_POINT)
73 DEFINE_STACK_OF_STRING()
74
75 typedef struct {
76 const char *name;
77 unsigned long flag;
78 unsigned long mask;
79 } NAME_EX_TBL;
80
81 static OPENSSL_CTX *app_libctx = NULL;
82
83 static int set_table_opts(unsigned long *flags, const char *arg,
84 const NAME_EX_TBL * in_tbl);
85 static int set_multi_opts(unsigned long *flags, const char *arg,
86 const NAME_EX_TBL * in_tbl);
87
88 int app_init(long mesgwin);
89
90 int chopup_args(ARGS *arg, char *buf)
91 {
92 int quoted;
93 char c = '\0', *p = NULL;
94
95 arg->argc = 0;
96 if (arg->size == 0) {
97 arg->size = 20;
98 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
99 }
100
101 for (p = buf;;) {
102 /* Skip whitespace. */
103 while (*p && isspace(_UC(*p)))
104 p++;
105 if (*p == '\0')
106 break;
107
108 /* The start of something good :-) */
109 if (arg->argc >= arg->size) {
110 char **tmp;
111 arg->size += 20;
112 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
113 if (tmp == NULL)
114 return 0;
115 arg->argv = tmp;
116 }
117 quoted = *p == '\'' || *p == '"';
118 if (quoted)
119 c = *p++;
120 arg->argv[arg->argc++] = p;
121
122 /* now look for the end of this */
123 if (quoted) {
124 while (*p && *p != c)
125 p++;
126 *p++ = '\0';
127 } else {
128 while (*p && !isspace(_UC(*p)))
129 p++;
130 if (*p)
131 *p++ = '\0';
132 }
133 }
134 arg->argv[arg->argc] = NULL;
135 return 1;
136 }
137
138 #ifndef APP_INIT
139 int app_init(long mesgwin)
140 {
141 return 1;
142 }
143 #endif
144
145 int ctx_set_verify_locations(SSL_CTX *ctx,
146 const char *CAfile, int noCAfile,
147 const char *CApath, int noCApath,
148 const char *CAstore, int noCAstore)
149 {
150 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
151 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
152 return 0;
153 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
154 return 0;
155 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
156 return 0;
157
158 return 1;
159 }
160
161 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
162 return 0;
163 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
164 return 0;
165 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
166 return 0;
167 return 1;
168 }
169
170 #ifndef OPENSSL_NO_CT
171
172 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
173 {
174 if (path == NULL)
175 return SSL_CTX_set_default_ctlog_list_file(ctx);
176
177 return SSL_CTX_set_ctlog_list_file(ctx, path);
178 }
179
180 #endif
181
182 static unsigned long nmflag = 0;
183 static char nmflag_set = 0;
184
185 int set_nameopt(const char *arg)
186 {
187 int ret = set_name_ex(&nmflag, arg);
188
189 if (ret)
190 nmflag_set = 1;
191
192 return ret;
193 }
194
195 unsigned long get_nameopt(void)
196 {
197 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
198 }
199
200 int dump_cert_text(BIO *out, X509 *x)
201 {
202 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
203 BIO_puts(out, "\n");
204 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
205 BIO_puts(out, "\n");
206
207 return 0;
208 }
209
210 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
211 {
212 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
213 }
214
215
216 static char *app_get_pass(const char *arg, int keepbio);
217
218 char *get_passwd(const char *pass, const char *desc)
219 {
220 char *result = NULL;
221
222 if (desc == NULL)
223 desc = "<unknown>";
224 if (!app_passwd(pass, NULL, &result, NULL))
225 BIO_printf(bio_err, "Error getting password for %s\n", desc);
226 if (pass != NULL && result == NULL) {
227 BIO_printf(bio_err,
228 "Trying plain input string (better precede with 'pass:')\n");
229 result = OPENSSL_strdup(pass);
230 if (result == NULL)
231 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
232 }
233 return result;
234 }
235
236 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
237 {
238 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
239
240 if (arg1 != NULL) {
241 *pass1 = app_get_pass(arg1, same);
242 if (*pass1 == NULL)
243 return 0;
244 } else if (pass1 != NULL) {
245 *pass1 = NULL;
246 }
247 if (arg2 != NULL) {
248 *pass2 = app_get_pass(arg2, same ? 2 : 0);
249 if (*pass2 == NULL)
250 return 0;
251 } else if (pass2 != NULL) {
252 *pass2 = NULL;
253 }
254 return 1;
255 }
256
257 static char *app_get_pass(const char *arg, int keepbio)
258 {
259 static BIO *pwdbio = NULL;
260 char *tmp, tpass[APP_PASS_LEN];
261 int i;
262
263 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
264 if (strncmp(arg, "pass:", 5) == 0)
265 return OPENSSL_strdup(arg + 5);
266 if (strncmp(arg, "env:", 4) == 0) {
267 tmp = getenv(arg + 4);
268 if (tmp == NULL) {
269 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
270 return NULL;
271 }
272 return OPENSSL_strdup(tmp);
273 }
274 if (!keepbio || pwdbio == NULL) {
275 if (strncmp(arg, "file:", 5) == 0) {
276 pwdbio = BIO_new_file(arg + 5, "r");
277 if (pwdbio == NULL) {
278 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
279 return NULL;
280 }
281 #if !defined(_WIN32)
282 /*
283 * Under _WIN32, which covers even Win64 and CE, file
284 * descriptors referenced by BIO_s_fd are not inherited
285 * by child process and therefore below is not an option.
286 * It could have been an option if bss_fd.c was operating
287 * on real Windows descriptors, such as those obtained
288 * with CreateFile.
289 */
290 } else if (strncmp(arg, "fd:", 3) == 0) {
291 BIO *btmp;
292 i = atoi(arg + 3);
293 if (i >= 0)
294 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
295 if ((i < 0) || !pwdbio) {
296 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
297 return NULL;
298 }
299 /*
300 * Can't do BIO_gets on an fd BIO so add a buffering BIO
301 */
302 btmp = BIO_new(BIO_f_buffer());
303 pwdbio = BIO_push(btmp, pwdbio);
304 #endif
305 } else if (strcmp(arg, "stdin") == 0) {
306 pwdbio = dup_bio_in(FORMAT_TEXT);
307 if (pwdbio == NULL) {
308 BIO_printf(bio_err, "Can't open BIO for stdin\n");
309 return NULL;
310 }
311 } else {
312 /* argument syntax error; do not reveal too much about arg */
313 tmp = strchr(arg, ':');
314 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
315 BIO_printf(bio_err,
316 "Invalid password argument, missing ':' within the first %d chars\n",
317 PASS_SOURCE_SIZE_MAX + 1);
318 else
319 BIO_printf(bio_err,
320 "Invalid password argument, starting with \"%.*s\"\n",
321 (int)(tmp - arg + 1), arg);
322 return NULL;
323 }
324 }
325 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
326 if (keepbio != 1) {
327 BIO_free_all(pwdbio);
328 pwdbio = NULL;
329 }
330 if (i <= 0) {
331 BIO_printf(bio_err, "Error reading password from BIO\n");
332 return NULL;
333 }
334 tmp = strchr(tpass, '\n');
335 if (tmp != NULL)
336 *tmp = 0;
337 return OPENSSL_strdup(tpass);
338 }
339
340 OPENSSL_CTX *app_get0_libctx(void)
341 {
342 return app_libctx;
343 }
344
345 /* TODO(3.0): Make this an environment variable if required */
346 const char *app_get0_propq(void)
347 {
348 return NULL;
349 }
350
351 OPENSSL_CTX *app_create_libctx(void)
352 {
353 /*
354 * Load the NULL provider into the default library context and create a
355 * library context which will then be used for any OPT_PROV options.
356 */
357 if (app_libctx == NULL) {
358
359 if (!app_provider_load(NULL, "null")) {
360 BIO_puts(bio_err, "Failed to create null provider\n");
361 return NULL;
362 }
363 app_libctx = OPENSSL_CTX_new();
364 }
365 if (app_libctx == NULL)
366 BIO_puts(bio_err, "Failed to create library context\n");
367 return app_libctx;
368 }
369
370 CONF *app_load_config_bio(BIO *in, const char *filename)
371 {
372 long errorline = -1;
373 CONF *conf;
374 int i;
375
376 conf = NCONF_new_with_libctx(app_libctx, NULL);
377 i = NCONF_load_bio(conf, in, &errorline);
378 if (i > 0)
379 return conf;
380
381 if (errorline <= 0) {
382 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
383 } else {
384 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
385 errorline);
386 }
387 if (filename != NULL)
388 BIO_printf(bio_err, "config file \"%s\"\n", filename);
389 else
390 BIO_printf(bio_err, "config input");
391
392 NCONF_free(conf);
393 return NULL;
394 }
395
396 CONF *app_load_config(const char *filename)
397 {
398 BIO *in;
399 CONF *conf;
400
401 in = bio_open_default(filename, 'r', FORMAT_TEXT);
402 if (in == NULL)
403 return NULL;
404
405 conf = app_load_config_bio(in, filename);
406 BIO_free(in);
407 return conf;
408 }
409
410 CONF *app_load_config_quiet(const char *filename)
411 {
412 BIO *in;
413 CONF *conf;
414
415 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
416 if (in == NULL)
417 return NULL;
418
419 conf = app_load_config_bio(in, filename);
420 BIO_free(in);
421 return conf;
422 }
423
424 int app_load_modules(const CONF *config)
425 {
426 CONF *to_free = NULL;
427
428 if (config == NULL)
429 config = to_free = app_load_config_quiet(default_config_file);
430 if (config == NULL)
431 return 1;
432
433 if (CONF_modules_load(config, NULL, 0) <= 0) {
434 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
435 ERR_print_errors(bio_err);
436 NCONF_free(to_free);
437 return 0;
438 }
439 NCONF_free(to_free);
440 return 1;
441 }
442
443 int add_oid_section(CONF *conf)
444 {
445 char *p;
446 STACK_OF(CONF_VALUE) *sktmp;
447 CONF_VALUE *cnf;
448 int i;
449
450 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
451 ERR_clear_error();
452 return 1;
453 }
454 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
455 BIO_printf(bio_err, "problem loading oid section %s\n", p);
456 return 0;
457 }
458 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
459 cnf = sk_CONF_VALUE_value(sktmp, i);
460 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
461 BIO_printf(bio_err, "problem creating object %s=%s\n",
462 cnf->name, cnf->value);
463 return 0;
464 }
465 }
466 return 1;
467 }
468
469 CONF *app_load_config_modules(const char *configfile)
470 {
471 CONF *conf = NULL;
472
473 if (configfile != NULL) {
474 BIO_printf(bio_err, "Using configuration from %s\n", configfile);
475
476 if ((conf = app_load_config(configfile)) == NULL)
477 return NULL;
478 if (configfile != default_config_file && !app_load_modules(conf)) {
479 NCONF_free(conf);
480 conf = NULL;
481 }
482 }
483 return conf;
484 }
485
486 X509 *load_cert_pass(const char *uri, int maybe_stdin,
487 const char *pass, const char *desc)
488 {
489 X509 *cert = NULL;
490
491 if (desc == NULL)
492 desc = "certificate";
493 (void)load_key_certs_crls(uri, maybe_stdin, pass, desc,
494 NULL, NULL, &cert, NULL, NULL, NULL);
495 if (cert == NULL) {
496 BIO_printf(bio_err, "Unable to load %s\n", desc);
497 ERR_print_errors(bio_err);
498 }
499 return cert;
500 }
501
502 /* the format parameter is meanwhile not needed anymore and thus ignored */
503 X509_CRL *load_crl(const char *uri, int format, const char *desc)
504 {
505 X509_CRL *crl = NULL;
506
507 if (desc == NULL)
508 desc = "CRL";
509 (void)load_key_certs_crls(uri, 0, NULL, desc,
510 NULL, NULL, NULL, NULL, &crl, NULL);
511 if (crl == NULL) {
512 BIO_printf(bio_err, "Unable to load %s\n", desc);
513 ERR_print_errors(bio_err);
514 }
515 return crl;
516 }
517
518 X509_REQ *load_csr(const char *file, int format, const char *desc)
519 {
520 X509_REQ *req = NULL;
521 BIO *in;
522
523 if (desc == NULL)
524 desc = "CSR";
525 in = bio_open_default(file, 'r', format);
526 if (in == NULL)
527 goto end;
528
529 if (format == FORMAT_ASN1)
530 req = d2i_X509_REQ_bio(in, NULL);
531 else if (format == FORMAT_PEM)
532 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
533 else
534 print_format_error(format, OPT_FMT_PEMDER);
535
536 end:
537 if (req == NULL) {
538 BIO_printf(bio_err, "Unable to load %s\n", desc);
539 ERR_print_errors(bio_err);
540 }
541 BIO_free(in);
542 return req;
543 }
544
545 void cleanse(char *str)
546 {
547 if (str != NULL)
548 OPENSSL_cleanse(str, strlen(str));
549 }
550
551 void clear_free(char *str)
552 {
553 if (str != NULL)
554 OPENSSL_clear_free(str, strlen(str));
555 }
556
557 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
558 const char *pass, ENGINE *e, const char *desc)
559 {
560 EVP_PKEY *pkey = NULL;
561
562 if (desc == NULL)
563 desc = "private key";
564
565 if (format == FORMAT_ENGINE) {
566 if (e == NULL) {
567 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
568 } else {
569 #ifndef OPENSSL_NO_ENGINE
570 PW_CB_DATA cb_data;
571
572 cb_data.password = pass;
573 cb_data.prompt_info = uri;
574 if (ENGINE_init(e)) {
575 pkey = ENGINE_load_private_key(e, uri,
576 (UI_METHOD *)get_ui_method(),
577 &cb_data);
578 ENGINE_finish(e);
579 }
580 if (pkey == NULL) {
581 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
582 ERR_print_errors(bio_err);
583 }
584 #else
585 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
586 #endif
587 }
588 } else {
589 (void)load_key_certs_crls(uri, may_stdin, pass, desc,
590 &pkey, NULL, NULL, NULL, NULL, NULL);
591 }
592
593 if (pkey == NULL) {
594 BIO_printf(bio_err, "Unable to load %s\n", desc);
595 ERR_print_errors(bio_err);
596 }
597 return pkey;
598 }
599
600 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
601 const char *pass, ENGINE *e, const char *desc)
602 {
603 EVP_PKEY *pkey = NULL;
604
605 if (desc == NULL)
606 desc = "public key";
607
608 if (format == FORMAT_ENGINE) {
609 if (e == NULL) {
610 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
611 } else {
612 #ifndef OPENSSL_NO_ENGINE
613 PW_CB_DATA cb_data;
614
615 cb_data.password = pass;
616 cb_data.prompt_info = uri;
617 pkey = ENGINE_load_public_key(e, uri, (UI_METHOD *)get_ui_method(),
618 &cb_data);
619 if (pkey == NULL) {
620 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
621 ERR_print_errors(bio_err);
622 }
623 #else
624 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
625 #endif
626 }
627 } else {
628 (void)load_key_certs_crls(uri, maybe_stdin, pass, desc,
629 NULL, &pkey, NULL, NULL, NULL, NULL);
630 }
631 if (pkey == NULL) {
632 BIO_printf(bio_err, "Unable to load %s\n", desc);
633 ERR_print_errors(bio_err);
634 }
635 return pkey;
636 }
637
638 void app_bail_out(char *fmt, ...)
639 {
640 va_list args;
641
642 va_start(args, fmt);
643 BIO_vprintf(bio_err, fmt, args);
644 va_end(args);
645 ERR_print_errors(bio_err);
646 exit(1);
647 }
648
649 void* app_malloc(int sz, const char *what)
650 {
651 void *vp = OPENSSL_malloc(sz);
652
653 if (vp == NULL)
654 app_bail_out("%s: Could not allocate %d bytes for %s\n",
655 opt_getprog(), sz, what);
656 return vp;
657 }
658
659 /*
660 * Initialize or extend, if *certs != NULL, a certificate stack.
661 * The caller is responsible for freeing *certs if its value is left not NULL.
662 */
663 int load_certs(const char *uri, STACK_OF(X509) **certs,
664 const char *pass, const char *desc)
665 {
666 int was_NULL = *certs == NULL;
667 int ret = load_key_certs_crls(uri, 0, pass, desc, NULL, NULL,
668 NULL, certs, NULL, NULL);
669
670 if (!ret && was_NULL) {
671 sk_X509_pop_free(*certs, X509_free);
672 *certs = NULL;
673 }
674 return ret;
675 }
676
677 /*
678 * Initialize or extend, if *crls != NULL, a certificate stack.
679 * The caller is responsible for freeing *crls if its value is left not NULL.
680 */
681 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
682 const char *pass, const char *desc)
683 {
684 int was_NULL = *crls == NULL;
685 int ret = load_key_certs_crls(uri, 0, pass, desc, NULL, NULL,
686 NULL, NULL, NULL, crls);
687
688 if (!ret && was_NULL) {
689 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
690 *crls = NULL;
691 }
692 return ret;
693 }
694
695 /*
696 * Load those types of credentials for which the result pointer is not NULL.
697 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
698 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
699 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
700 * If pcerts is non-NULL then all available certificates are appended to *pcerts
701 * except any certificate assigned to *pcert.
702 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
703 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
704 * except any CRL assigned to *pcrl.
705 * In any case (also on error) the caller is responsible for freeing all members
706 * of *pcerts and *pcrls (as far as they are not NULL).
707 */
708 int load_key_certs_crls(const char *uri, int maybe_stdin,
709 const char *pass, const char *desc,
710 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
711 X509 **pcert, STACK_OF(X509) **pcerts,
712 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
713 {
714 PW_CB_DATA uidata;
715 OSSL_STORE_CTX *ctx = NULL;
716 OPENSSL_CTX *libctx = app_get0_libctx();
717 const char *propq = app_get0_propq();
718 int ncerts = 0;
719 int ncrls = 0;
720 const char *failed = "any";
721 /* TODO make use of the engine reference 'eng' when loading pkeys */
722
723 if (ppkey != NULL)
724 *ppkey = NULL;
725 if (ppubkey != NULL)
726 *ppubkey = NULL;
727 if (pcert != NULL)
728 *pcert = NULL;
729 if (pcerts != NULL && *pcerts == NULL
730 && (*pcerts = sk_X509_new_null()) == NULL) {
731 BIO_printf(bio_err, "Out of memory");
732 goto end;
733 }
734 if (pcrl != NULL)
735 *pcrl = NULL;
736 if (pcrls != NULL && *pcrls == NULL
737 && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
738 BIO_printf(bio_err, "Out of memory");
739 goto end;
740 }
741
742 if (desc == NULL)
743 desc = "key/certificate/CRL";
744 uidata.password = pass;
745 uidata.prompt_info = uri;
746
747 if (uri == NULL) {
748 BIO *bio;
749
750 uri = "<stdin>";
751 if (!maybe_stdin) {
752 BIO_printf(bio_err, "No filename or uri specified for loading %s\n",
753 desc);
754 goto end;
755 }
756 unbuffer(stdin);
757 bio = BIO_new_fp(stdin, 0);
758 if (bio != NULL)
759 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
760 get_ui_method(), &uidata, NULL, NULL);
761 } else {
762 ctx = OSSL_STORE_open_with_libctx(uri, libctx, propq, get_ui_method(),
763 &uidata, NULL, NULL);
764 }
765 if (ctx == NULL) {
766 BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
767 uri, desc);
768 goto end;
769 }
770
771 failed = NULL;
772 while (!OSSL_STORE_eof(ctx)) {
773 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
774 int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
775 int ok = 1;
776
777 switch (type) {
778 case OSSL_STORE_INFO_PKEY:
779 if (ppkey != NULL && *ppkey == NULL)
780 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
781
782 /*
783 * An EVP_PKEY with private parts also holds the public parts,
784 * so if the caller asked for a public key, and we got a private
785 * key, we can still pass it back.
786 */
787 if (ok && ppubkey != NULL && *ppubkey == NULL)
788 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
789 break;
790 case OSSL_STORE_INFO_PUBKEY:
791 if (ppubkey != NULL && *ppubkey == NULL)
792 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
793 break;
794 case OSSL_STORE_INFO_CERT:
795 if (pcert != NULL && *pcert == NULL)
796 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
797 else if (pcerts != NULL)
798 ok = X509_add_cert(*pcerts,
799 OSSL_STORE_INFO_get1_CERT(info),
800 X509_ADD_FLAG_DEFAULT);
801 ncerts += ok;
802 break;
803 case OSSL_STORE_INFO_CRL:
804 if (pcrl != NULL && *pcrl == NULL)
805 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
806 else if (pcrls != NULL)
807 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
808 ncrls += ok;
809 break;
810 default:
811 /* skip any other type */
812 break;
813 }
814 OSSL_STORE_INFO_free(info);
815 if (!ok) {
816 failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
817 BIO_printf(bio_err, "Error reading %s of %s from %s\n",
818 failed, desc, uri);
819 break;
820 }
821 }
822
823 end:
824 OSSL_STORE_close(ctx);
825 if (failed == NULL) {
826 if (ppkey != NULL && *ppkey == NULL)
827 failed = "key";
828 else if ((pcert != NULL || pcerts != NULL) && ncerts == 0)
829 failed = "cert";
830 else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0)
831 failed = "CRL";
832 if (failed != NULL)
833 BIO_printf(bio_err, "Could not read any %s of %s from %s\n",
834 failed, desc, uri);
835 }
836 if (failed != NULL)
837 ERR_print_errors(bio_err);
838 return failed == NULL;
839 }
840
841
842 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
843 /* Return error for unknown extensions */
844 #define X509V3_EXT_DEFAULT 0
845 /* Print error for unknown extensions */
846 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
847 /* ASN1 parse unknown extensions */
848 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
849 /* BIO_dump unknown extensions */
850 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
851
852 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
853 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
854
855 int set_cert_ex(unsigned long *flags, const char *arg)
856 {
857 static const NAME_EX_TBL cert_tbl[] = {
858 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
859 {"ca_default", X509_FLAG_CA, 0xffffffffl},
860 {"no_header", X509_FLAG_NO_HEADER, 0},
861 {"no_version", X509_FLAG_NO_VERSION, 0},
862 {"no_serial", X509_FLAG_NO_SERIAL, 0},
863 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
864 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
865 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
866 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
867 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
868 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
869 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
870 {"no_aux", X509_FLAG_NO_AUX, 0},
871 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
872 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
873 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
874 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
875 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
876 {NULL, 0, 0}
877 };
878 return set_multi_opts(flags, arg, cert_tbl);
879 }
880
881 int set_name_ex(unsigned long *flags, const char *arg)
882 {
883 static const NAME_EX_TBL ex_tbl[] = {
884 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
885 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
886 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
887 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
888 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
889 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
890 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
891 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
892 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
893 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
894 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
895 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
896 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
897 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
898 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
899 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
900 {"dn_rev", XN_FLAG_DN_REV, 0},
901 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
902 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
903 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
904 {"align", XN_FLAG_FN_ALIGN, 0},
905 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
906 {"space_eq", XN_FLAG_SPC_EQ, 0},
907 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
908 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
909 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
910 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
911 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
912 {NULL, 0, 0}
913 };
914 if (set_multi_opts(flags, arg, ex_tbl) == 0)
915 return 0;
916 if (*flags != XN_FLAG_COMPAT
917 && (*flags & XN_FLAG_SEP_MASK) == 0)
918 *flags |= XN_FLAG_SEP_CPLUS_SPC;
919 return 1;
920 }
921
922 int set_ext_copy(int *copy_type, const char *arg)
923 {
924 if (strcasecmp(arg, "none") == 0)
925 *copy_type = EXT_COPY_NONE;
926 else if (strcasecmp(arg, "copy") == 0)
927 *copy_type = EXT_COPY_ADD;
928 else if (strcasecmp(arg, "copyall") == 0)
929 *copy_type = EXT_COPY_ALL;
930 else
931 return 0;
932 return 1;
933 }
934
935 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
936 {
937 STACK_OF(X509_EXTENSION) *exts = NULL;
938 X509_EXTENSION *ext, *tmpext;
939 ASN1_OBJECT *obj;
940 int i, idx, ret = 0;
941 if (!x || !req || (copy_type == EXT_COPY_NONE))
942 return 1;
943 exts = X509_REQ_get_extensions(req);
944
945 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
946 ext = sk_X509_EXTENSION_value(exts, i);
947 obj = X509_EXTENSION_get_object(ext);
948 idx = X509_get_ext_by_OBJ(x, obj, -1);
949 /* Does extension exist? */
950 if (idx != -1) {
951 /* If normal copy don't override existing extension */
952 if (copy_type == EXT_COPY_ADD)
953 continue;
954 /* Delete all extensions of same type */
955 do {
956 tmpext = X509_get_ext(x, idx);
957 X509_delete_ext(x, idx);
958 X509_EXTENSION_free(tmpext);
959 idx = X509_get_ext_by_OBJ(x, obj, -1);
960 } while (idx != -1);
961 }
962 if (!X509_add_ext(x, ext, -1))
963 goto end;
964 }
965
966 ret = 1;
967
968 end:
969
970 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
971
972 return ret;
973 }
974
975 static int set_multi_opts(unsigned long *flags, const char *arg,
976 const NAME_EX_TBL * in_tbl)
977 {
978 STACK_OF(CONF_VALUE) *vals;
979 CONF_VALUE *val;
980 int i, ret = 1;
981 if (!arg)
982 return 0;
983 vals = X509V3_parse_list(arg);
984 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
985 val = sk_CONF_VALUE_value(vals, i);
986 if (!set_table_opts(flags, val->name, in_tbl))
987 ret = 0;
988 }
989 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
990 return ret;
991 }
992
993 static int set_table_opts(unsigned long *flags, const char *arg,
994 const NAME_EX_TBL * in_tbl)
995 {
996 char c;
997 const NAME_EX_TBL *ptbl;
998 c = arg[0];
999
1000 if (c == '-') {
1001 c = 0;
1002 arg++;
1003 } else if (c == '+') {
1004 c = 1;
1005 arg++;
1006 } else {
1007 c = 1;
1008 }
1009
1010 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1011 if (strcasecmp(arg, ptbl->name) == 0) {
1012 *flags &= ~ptbl->mask;
1013 if (c)
1014 *flags |= ptbl->flag;
1015 else
1016 *flags &= ~ptbl->flag;
1017 return 1;
1018 }
1019 }
1020 return 0;
1021 }
1022
1023 void print_name(BIO *out, const char *title, const X509_NAME *nm,
1024 unsigned long lflags)
1025 {
1026 char *buf;
1027 char mline = 0;
1028 int indent = 0;
1029
1030 if (title)
1031 BIO_puts(out, title);
1032 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1033 mline = 1;
1034 indent = 4;
1035 }
1036 if (lflags == XN_FLAG_COMPAT) {
1037 buf = X509_NAME_oneline(nm, 0, 0);
1038 BIO_puts(out, buf);
1039 BIO_puts(out, "\n");
1040 OPENSSL_free(buf);
1041 } else {
1042 if (mline)
1043 BIO_puts(out, "\n");
1044 X509_NAME_print_ex(out, nm, indent, lflags);
1045 BIO_puts(out, "\n");
1046 }
1047 }
1048
1049 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1050 int len, unsigned char *buffer)
1051 {
1052 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1053 if (BN_is_zero(in)) {
1054 BIO_printf(out, "\n 0x00");
1055 } else {
1056 int i, l;
1057
1058 l = BN_bn2bin(in, buffer);
1059 for (i = 0; i < l; i++) {
1060 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1061 if (i < l - 1)
1062 BIO_printf(out, "0x%02X,", buffer[i]);
1063 else
1064 BIO_printf(out, "0x%02X", buffer[i]);
1065 }
1066 }
1067 BIO_printf(out, "\n };\n");
1068 }
1069
1070 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1071 {
1072 int i;
1073
1074 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1075 for (i = 0; i < len; i++) {
1076 if ((i % 10) == 0)
1077 BIO_printf(out, "\n ");
1078 if (i < len - 1)
1079 BIO_printf(out, "0x%02X, ", d[i]);
1080 else
1081 BIO_printf(out, "0x%02X", d[i]);
1082 }
1083 BIO_printf(out, "\n};\n");
1084 }
1085
1086 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1087 const char *CApath, int noCApath,
1088 const char *CAstore, int noCAstore)
1089 {
1090 X509_STORE *store = X509_STORE_new();
1091 X509_LOOKUP *lookup;
1092 OPENSSL_CTX *libctx = app_get0_libctx();
1093 const char *propq = app_get0_propq();
1094
1095 if (store == NULL)
1096 goto end;
1097
1098 if (CAfile != NULL || !noCAfile) {
1099 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1100 if (lookup == NULL)
1101 goto end;
1102 if (CAfile != NULL) {
1103 if (!X509_LOOKUP_load_file_with_libctx(lookup, CAfile,
1104 X509_FILETYPE_PEM,
1105 libctx, propq)) {
1106 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1107 goto end;
1108 }
1109 } else {
1110 X509_LOOKUP_load_file_with_libctx(lookup, NULL,
1111 X509_FILETYPE_DEFAULT,
1112 libctx, propq);
1113 }
1114 }
1115
1116 if (CApath != NULL || !noCApath) {
1117 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1118 if (lookup == NULL)
1119 goto end;
1120 if (CApath != NULL) {
1121 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1122 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1123 goto end;
1124 }
1125 } else {
1126 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1127 }
1128 }
1129
1130 if (CAstore != NULL || !noCAstore) {
1131 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1132 if (lookup == NULL)
1133 goto end;
1134 if (!X509_LOOKUP_add_store_with_libctx(lookup, CAstore, libctx, propq)) {
1135 if (CAstore != NULL)
1136 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1137 goto end;
1138 }
1139 }
1140
1141 ERR_clear_error();
1142 return store;
1143 end:
1144 ERR_print_errors(bio_err);
1145 X509_STORE_free(store);
1146 return NULL;
1147 }
1148
1149 #ifndef OPENSSL_NO_ENGINE
1150 /* Try to load an engine in a shareable library */
1151 static ENGINE *try_load_engine(const char *engine)
1152 {
1153 ENGINE *e = ENGINE_by_id("dynamic");
1154 if (e) {
1155 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1156 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1157 ENGINE_free(e);
1158 e = NULL;
1159 }
1160 }
1161 return e;
1162 }
1163 #endif
1164
1165 ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
1166 {
1167 ENGINE *e = NULL;
1168
1169 #ifndef OPENSSL_NO_ENGINE
1170 if (id != NULL) {
1171 if (strcmp(id, "auto") == 0) {
1172 BIO_printf(bio_err, "Enabling auto ENGINE support\n");
1173 ENGINE_register_all_complete();
1174 return NULL;
1175 }
1176 if ((e = ENGINE_by_id(id)) == NULL
1177 && (e = try_load_engine(id)) == NULL) {
1178 BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
1179 ERR_print_errors(bio_err);
1180 return NULL;
1181 }
1182 if (debug)
1183 (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1184 if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
1185 (void *)get_ui_method(), 0, 1)
1186 || !ENGINE_set_default(e, methods)) {
1187 BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
1188 ERR_print_errors(bio_err);
1189 ENGINE_free(e);
1190 return NULL;
1191 }
1192
1193 BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
1194 }
1195 #endif
1196 return e;
1197 }
1198
1199 void release_engine(ENGINE *e)
1200 {
1201 #ifndef OPENSSL_NO_ENGINE
1202 /* Free our "structural" reference. */
1203 ENGINE_free(e);
1204 #endif
1205 }
1206
1207 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1208 {
1209 const char *n;
1210
1211 n = a[DB_serial];
1212 while (*n == '0')
1213 n++;
1214 return OPENSSL_LH_strhash(n);
1215 }
1216
1217 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1218 const OPENSSL_CSTRING *b)
1219 {
1220 const char *aa, *bb;
1221
1222 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1223 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1224 return strcmp(aa, bb);
1225 }
1226
1227 static int index_name_qual(char **a)
1228 {
1229 return (a[0][0] == 'V');
1230 }
1231
1232 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1233 {
1234 return OPENSSL_LH_strhash(a[DB_name]);
1235 }
1236
1237 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1238 {
1239 return strcmp(a[DB_name], b[DB_name]);
1240 }
1241
1242 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1243 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1244 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1245 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1246 #undef BSIZE
1247 #define BSIZE 256
1248 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1249 {
1250 BIO *in = NULL;
1251 BIGNUM *ret = NULL;
1252 char buf[1024];
1253 ASN1_INTEGER *ai = NULL;
1254
1255 ai = ASN1_INTEGER_new();
1256 if (ai == NULL)
1257 goto err;
1258
1259 in = BIO_new_file(serialfile, "r");
1260 if (in == NULL) {
1261 if (!create) {
1262 perror(serialfile);
1263 goto err;
1264 }
1265 ERR_clear_error();
1266 ret = BN_new();
1267 if (ret == NULL || !rand_serial(ret, ai))
1268 BIO_printf(bio_err, "Out of memory\n");
1269 } else {
1270 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1271 BIO_printf(bio_err, "Unable to load number from %s\n",
1272 serialfile);
1273 goto err;
1274 }
1275 ret = ASN1_INTEGER_to_BN(ai, NULL);
1276 if (ret == NULL) {
1277 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1278 goto err;
1279 }
1280 }
1281
1282 if (ret && retai) {
1283 *retai = ai;
1284 ai = NULL;
1285 }
1286 err:
1287 ERR_print_errors(bio_err);
1288 BIO_free(in);
1289 ASN1_INTEGER_free(ai);
1290 return ret;
1291 }
1292
1293 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1294 ASN1_INTEGER **retai)
1295 {
1296 char buf[1][BSIZE];
1297 BIO *out = NULL;
1298 int ret = 0;
1299 ASN1_INTEGER *ai = NULL;
1300 int j;
1301
1302 if (suffix == NULL)
1303 j = strlen(serialfile);
1304 else
1305 j = strlen(serialfile) + strlen(suffix) + 1;
1306 if (j >= BSIZE) {
1307 BIO_printf(bio_err, "File name too long\n");
1308 goto err;
1309 }
1310
1311 if (suffix == NULL)
1312 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1313 else {
1314 #ifndef OPENSSL_SYS_VMS
1315 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1316 #else
1317 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1318 #endif
1319 }
1320 out = BIO_new_file(buf[0], "w");
1321 if (out == NULL) {
1322 goto err;
1323 }
1324
1325 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1326 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1327 goto err;
1328 }
1329 i2a_ASN1_INTEGER(out, ai);
1330 BIO_puts(out, "\n");
1331 ret = 1;
1332 if (retai) {
1333 *retai = ai;
1334 ai = NULL;
1335 }
1336 err:
1337 if (!ret)
1338 ERR_print_errors(bio_err);
1339 BIO_free_all(out);
1340 ASN1_INTEGER_free(ai);
1341 return ret;
1342 }
1343
1344 int rotate_serial(const char *serialfile, const char *new_suffix,
1345 const char *old_suffix)
1346 {
1347 char buf[2][BSIZE];
1348 int i, j;
1349
1350 i = strlen(serialfile) + strlen(old_suffix);
1351 j = strlen(serialfile) + strlen(new_suffix);
1352 if (i > j)
1353 j = i;
1354 if (j + 1 >= BSIZE) {
1355 BIO_printf(bio_err, "File name too long\n");
1356 goto err;
1357 }
1358 #ifndef OPENSSL_SYS_VMS
1359 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1360 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1361 #else
1362 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1363 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1364 #endif
1365 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1366 #ifdef ENOTDIR
1367 && errno != ENOTDIR
1368 #endif
1369 ) {
1370 BIO_printf(bio_err,
1371 "Unable to rename %s to %s\n", serialfile, buf[1]);
1372 perror("reason");
1373 goto err;
1374 }
1375 if (rename(buf[0], serialfile) < 0) {
1376 BIO_printf(bio_err,
1377 "Unable to rename %s to %s\n", buf[0], serialfile);
1378 perror("reason");
1379 rename(buf[1], serialfile);
1380 goto err;
1381 }
1382 return 1;
1383 err:
1384 ERR_print_errors(bio_err);
1385 return 0;
1386 }
1387
1388 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1389 {
1390 BIGNUM *btmp;
1391 int ret = 0;
1392
1393 btmp = b == NULL ? BN_new() : b;
1394 if (btmp == NULL)
1395 return 0;
1396
1397 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1398 goto error;
1399 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1400 goto error;
1401
1402 ret = 1;
1403
1404 error:
1405
1406 if (btmp != b)
1407 BN_free(btmp);
1408
1409 return ret;
1410 }
1411
1412 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1413 {
1414 CA_DB *retdb = NULL;
1415 TXT_DB *tmpdb = NULL;
1416 BIO *in;
1417 CONF *dbattr_conf = NULL;
1418 char buf[BSIZE];
1419 #ifndef OPENSSL_NO_POSIX_IO
1420 FILE *dbfp;
1421 struct stat dbst;
1422 #endif
1423
1424 in = BIO_new_file(dbfile, "r");
1425 if (in == NULL)
1426 goto err;
1427
1428 #ifndef OPENSSL_NO_POSIX_IO
1429 BIO_get_fp(in, &dbfp);
1430 if (fstat(fileno(dbfp), &dbst) == -1) {
1431 ERR_raise_data(ERR_LIB_SYS, errno,
1432 "calling fstat(%s)", dbfile);
1433 goto err;
1434 }
1435 #endif
1436
1437 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1438 goto err;
1439
1440 #ifndef OPENSSL_SYS_VMS
1441 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1442 #else
1443 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1444 #endif
1445 dbattr_conf = app_load_config_quiet(buf);
1446
1447 retdb = app_malloc(sizeof(*retdb), "new DB");
1448 retdb->db = tmpdb;
1449 tmpdb = NULL;
1450 if (db_attr)
1451 retdb->attributes = *db_attr;
1452 else {
1453 retdb->attributes.unique_subject = 1;
1454 }
1455
1456 if (dbattr_conf) {
1457 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1458 if (p) {
1459 retdb->attributes.unique_subject = parse_yesno(p, 1);
1460 }
1461 }
1462
1463 retdb->dbfname = OPENSSL_strdup(dbfile);
1464 #ifndef OPENSSL_NO_POSIX_IO
1465 retdb->dbst = dbst;
1466 #endif
1467
1468 err:
1469 ERR_print_errors(bio_err);
1470 NCONF_free(dbattr_conf);
1471 TXT_DB_free(tmpdb);
1472 BIO_free_all(in);
1473 return retdb;
1474 }
1475
1476 /*
1477 * Returns > 0 on success, <= 0 on error
1478 */
1479 int index_index(CA_DB *db)
1480 {
1481 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1482 LHASH_HASH_FN(index_serial),
1483 LHASH_COMP_FN(index_serial))) {
1484 BIO_printf(bio_err,
1485 "Error creating serial number index:(%ld,%ld,%ld)\n",
1486 db->db->error, db->db->arg1, db->db->arg2);
1487 goto err;
1488 }
1489
1490 if (db->attributes.unique_subject
1491 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1492 LHASH_HASH_FN(index_name),
1493 LHASH_COMP_FN(index_name))) {
1494 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1495 db->db->error, db->db->arg1, db->db->arg2);
1496 goto err;
1497 }
1498 return 1;
1499 err:
1500 ERR_print_errors(bio_err);
1501 return 0;
1502 }
1503
1504 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1505 {
1506 char buf[3][BSIZE];
1507 BIO *out;
1508 int j;
1509
1510 j = strlen(dbfile) + strlen(suffix);
1511 if (j + 6 >= BSIZE) {
1512 BIO_printf(bio_err, "File name too long\n");
1513 goto err;
1514 }
1515 #ifndef OPENSSL_SYS_VMS
1516 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1517 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1518 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1519 #else
1520 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1521 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1522 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1523 #endif
1524 out = BIO_new_file(buf[0], "w");
1525 if (out == NULL) {
1526 perror(dbfile);
1527 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1528 goto err;
1529 }
1530 j = TXT_DB_write(out, db->db);
1531 BIO_free(out);
1532 if (j <= 0)
1533 goto err;
1534
1535 out = BIO_new_file(buf[1], "w");
1536 if (out == NULL) {
1537 perror(buf[2]);
1538 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1539 goto err;
1540 }
1541 BIO_printf(out, "unique_subject = %s\n",
1542 db->attributes.unique_subject ? "yes" : "no");
1543 BIO_free(out);
1544
1545 return 1;
1546 err:
1547 ERR_print_errors(bio_err);
1548 return 0;
1549 }
1550
1551 int rotate_index(const char *dbfile, const char *new_suffix,
1552 const char *old_suffix)
1553 {
1554 char buf[5][BSIZE];
1555 int i, j;
1556
1557 i = strlen(dbfile) + strlen(old_suffix);
1558 j = strlen(dbfile) + strlen(new_suffix);
1559 if (i > j)
1560 j = i;
1561 if (j + 6 >= BSIZE) {
1562 BIO_printf(bio_err, "File name too long\n");
1563 goto err;
1564 }
1565 #ifndef OPENSSL_SYS_VMS
1566 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1567 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1568 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1569 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1570 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1571 #else
1572 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1573 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1574 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1575 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1576 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1577 #endif
1578 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1579 #ifdef ENOTDIR
1580 && errno != ENOTDIR
1581 #endif
1582 ) {
1583 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1584 perror("reason");
1585 goto err;
1586 }
1587 if (rename(buf[0], dbfile) < 0) {
1588 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1589 perror("reason");
1590 rename(buf[1], dbfile);
1591 goto err;
1592 }
1593 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1594 #ifdef ENOTDIR
1595 && errno != ENOTDIR
1596 #endif
1597 ) {
1598 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1599 perror("reason");
1600 rename(dbfile, buf[0]);
1601 rename(buf[1], dbfile);
1602 goto err;
1603 }
1604 if (rename(buf[2], buf[4]) < 0) {
1605 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1606 perror("reason");
1607 rename(buf[3], buf[4]);
1608 rename(dbfile, buf[0]);
1609 rename(buf[1], dbfile);
1610 goto err;
1611 }
1612 return 1;
1613 err:
1614 ERR_print_errors(bio_err);
1615 return 0;
1616 }
1617
1618 void free_index(CA_DB *db)
1619 {
1620 if (db) {
1621 TXT_DB_free(db->db);
1622 OPENSSL_free(db->dbfname);
1623 OPENSSL_free(db);
1624 }
1625 }
1626
1627 int parse_yesno(const char *str, int def)
1628 {
1629 if (str) {
1630 switch (*str) {
1631 case 'f': /* false */
1632 case 'F': /* FALSE */
1633 case 'n': /* no */
1634 case 'N': /* NO */
1635 case '0': /* 0 */
1636 return 0;
1637 case 't': /* true */
1638 case 'T': /* TRUE */
1639 case 'y': /* yes */
1640 case 'Y': /* YES */
1641 case '1': /* 1 */
1642 return 1;
1643 }
1644 }
1645 return def;
1646 }
1647
1648 /*
1649 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1650 * where + can be used instead of / to form multi-valued RDNs if canmulti
1651 * and characters may be escaped by \
1652 */
1653 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1654 const char *desc)
1655 {
1656 int nextismulti = 0;
1657 char *work;
1658 X509_NAME *n;
1659
1660 if (*cp++ != '/') {
1661 BIO_printf(bio_err,
1662 "%s: %s name is expected to be in the format "
1663 "/type0=value0/type1=value1/type2=... where characters may "
1664 "be escaped by \\. This name is not in that format: '%s'\n",
1665 opt_getprog(), desc, --cp);
1666 return NULL;
1667 }
1668
1669 n = X509_NAME_new();
1670 if (n == NULL) {
1671 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1672 return NULL;
1673 }
1674 work = OPENSSL_strdup(cp);
1675 if (work == NULL) {
1676 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1677 opt_getprog(), desc);
1678 goto err;
1679 }
1680
1681 while (*cp != '\0') {
1682 char *bp = work;
1683 char *typestr = bp;
1684 unsigned char *valstr;
1685 int nid;
1686 int ismulti = nextismulti;
1687 nextismulti = 0;
1688
1689 /* Collect the type */
1690 while (*cp != '\0' && *cp != '=')
1691 *bp++ = *cp++;
1692 *bp++ = '\0';
1693 if (*cp == '\0') {
1694 BIO_printf(bio_err,
1695 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1696 opt_getprog(), typestr, desc);
1697 goto err;
1698 }
1699 ++cp;
1700
1701 /* Collect the value. */
1702 valstr = (unsigned char *)bp;
1703 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1704 /* unescaped '+' symbol string signals further member of multiRDN */
1705 if (canmulti && *cp == '+') {
1706 nextismulti = 1;
1707 break;
1708 }
1709 if (*cp == '\\' && *++cp == '\0') {
1710 BIO_printf(bio_err,
1711 "%s: Escape character at end of %s name string\n",
1712 opt_getprog(), desc);
1713 goto err;
1714 }
1715 }
1716 *bp++ = '\0';
1717
1718 /* If not at EOS (must be + or /), move forward. */
1719 if (*cp != '\0')
1720 ++cp;
1721
1722 /* Parse */
1723 nid = OBJ_txt2nid(typestr);
1724 if (nid == NID_undef) {
1725 BIO_printf(bio_err,
1726 "%s: Skipping unknown %s name attribute \"%s\"\n",
1727 opt_getprog(), desc, typestr);
1728 if (ismulti)
1729 BIO_printf(bio_err,
1730 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1731 continue;
1732 }
1733 if (*valstr == '\0') {
1734 BIO_printf(bio_err,
1735 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1736 opt_getprog(), desc, typestr);
1737 continue;
1738 }
1739 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1740 valstr, strlen((char *)valstr),
1741 -1, ismulti ? -1 : 0)) {
1742 ERR_print_errors(bio_err);
1743 BIO_printf(bio_err,
1744 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1745 opt_getprog(), desc, typestr ,valstr);
1746 goto err;
1747 }
1748 }
1749
1750 OPENSSL_free(work);
1751 return n;
1752
1753 err:
1754 X509_NAME_free(n);
1755 OPENSSL_free(work);
1756 return NULL;
1757 }
1758
1759 /*
1760 * Read whole contents of a BIO into an allocated memory buffer and return
1761 * it.
1762 */
1763
1764 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1765 {
1766 BIO *mem;
1767 int len, ret;
1768 unsigned char tbuf[1024];
1769
1770 mem = BIO_new(BIO_s_mem());
1771 if (mem == NULL)
1772 return -1;
1773 for (;;) {
1774 if ((maxlen != -1) && maxlen < 1024)
1775 len = maxlen;
1776 else
1777 len = 1024;
1778 len = BIO_read(in, tbuf, len);
1779 if (len < 0) {
1780 BIO_free(mem);
1781 return -1;
1782 }
1783 if (len == 0)
1784 break;
1785 if (BIO_write(mem, tbuf, len) != len) {
1786 BIO_free(mem);
1787 return -1;
1788 }
1789 maxlen -= len;
1790
1791 if (maxlen == 0)
1792 break;
1793 }
1794 ret = BIO_get_mem_data(mem, (char **)out);
1795 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1796 BIO_free(mem);
1797 return ret;
1798 }
1799
1800 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1801 {
1802 int rv;
1803 char *stmp, *vtmp = NULL;
1804 stmp = OPENSSL_strdup(value);
1805 if (!stmp)
1806 return -1;
1807 vtmp = strchr(stmp, ':');
1808 if (vtmp) {
1809 *vtmp = 0;
1810 vtmp++;
1811 }
1812 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1813 OPENSSL_free(stmp);
1814 return rv;
1815 }
1816
1817 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1818 {
1819 X509_POLICY_NODE *node;
1820 int i;
1821
1822 BIO_printf(bio_err, "%s Policies:", name);
1823 if (nodes) {
1824 BIO_puts(bio_err, "\n");
1825 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1826 node = sk_X509_POLICY_NODE_value(nodes, i);
1827 X509_POLICY_NODE_print(bio_err, node, 2);
1828 }
1829 } else {
1830 BIO_puts(bio_err, " <empty>\n");
1831 }
1832 }
1833
1834 void policies_print(X509_STORE_CTX *ctx)
1835 {
1836 X509_POLICY_TREE *tree;
1837 int explicit_policy;
1838 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1839 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1840
1841 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1842 explicit_policy ? "True" : "False");
1843
1844 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1845 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1846 }
1847
1848 /*-
1849 * next_protos_parse parses a comma separated list of strings into a string
1850 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1851 * outlen: (output) set to the length of the resulting buffer on success.
1852 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1853 * in: a NUL terminated string like "abc,def,ghi"
1854 *
1855 * returns: a malloc'd buffer or NULL on failure.
1856 */
1857 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1858 {
1859 size_t len;
1860 unsigned char *out;
1861 size_t i, start = 0;
1862 size_t skipped = 0;
1863
1864 len = strlen(in);
1865 if (len == 0 || len >= 65535)
1866 return NULL;
1867
1868 out = app_malloc(len + 1, "NPN buffer");
1869 for (i = 0; i <= len; ++i) {
1870 if (i == len || in[i] == ',') {
1871 /*
1872 * Zero-length ALPN elements are invalid on the wire, we could be
1873 * strict and reject the entire string, but just ignoring extra
1874 * commas seems harmless and more friendly.
1875 *
1876 * Every comma we skip in this way puts the input buffer another
1877 * byte ahead of the output buffer, so all stores into the output
1878 * buffer need to be decremented by the number commas skipped.
1879 */
1880 if (i == start) {
1881 ++start;
1882 ++skipped;
1883 continue;
1884 }
1885 if (i - start > 255) {
1886 OPENSSL_free(out);
1887 return NULL;
1888 }
1889 out[start-skipped] = (unsigned char)(i - start);
1890 start = i + 1;
1891 } else {
1892 out[i + 1 - skipped] = in[i];
1893 }
1894 }
1895
1896 if (len <= skipped) {
1897 OPENSSL_free(out);
1898 return NULL;
1899 }
1900
1901 *outlen = len + 1 - skipped;
1902 return out;
1903 }
1904
1905 void print_cert_checks(BIO *bio, X509 *x,
1906 const char *checkhost,
1907 const char *checkemail, const char *checkip)
1908 {
1909 if (x == NULL)
1910 return;
1911 if (checkhost) {
1912 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1913 checkhost,
1914 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1915 ? "" : " NOT");
1916 }
1917
1918 if (checkemail) {
1919 BIO_printf(bio, "Email %s does%s match certificate\n",
1920 checkemail, X509_check_email(x, checkemail, 0, 0)
1921 ? "" : " NOT");
1922 }
1923
1924 if (checkip) {
1925 BIO_printf(bio, "IP %s does%s match certificate\n",
1926 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1927 }
1928 }
1929
1930 /* Get first http URL from a DIST_POINT structure */
1931
1932 static const char *get_dp_url(DIST_POINT *dp)
1933 {
1934 GENERAL_NAMES *gens;
1935 GENERAL_NAME *gen;
1936 int i, gtype;
1937 ASN1_STRING *uri;
1938 if (!dp->distpoint || dp->distpoint->type != 0)
1939 return NULL;
1940 gens = dp->distpoint->name.fullname;
1941 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1942 gen = sk_GENERAL_NAME_value(gens, i);
1943 uri = GENERAL_NAME_get0_value(gen, &gtype);
1944 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1945 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1946 if (strncmp(uptr, "http://", 7) == 0)
1947 return uptr;
1948 }
1949 }
1950 return NULL;
1951 }
1952
1953 /*
1954 * Look through a CRLDP structure and attempt to find an http URL to
1955 * downloads a CRL from.
1956 */
1957
1958 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1959 {
1960 int i;
1961 const char *urlptr = NULL;
1962 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1963 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1964 urlptr = get_dp_url(dp);
1965 if (urlptr)
1966 return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1967 }
1968 return NULL;
1969 }
1970
1971 /*
1972 * Example of downloading CRLs from CRLDP:
1973 * not usable for real world as it always downloads and doesn't cache anything.
1974 */
1975
1976 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1977 const X509_NAME *nm)
1978 {
1979 X509 *x;
1980 STACK_OF(X509_CRL) *crls = NULL;
1981 X509_CRL *crl;
1982 STACK_OF(DIST_POINT) *crldp;
1983
1984 crls = sk_X509_CRL_new_null();
1985 if (!crls)
1986 return NULL;
1987 x = X509_STORE_CTX_get_current_cert(ctx);
1988 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1989 crl = load_crl_crldp(crldp);
1990 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1991 if (!crl) {
1992 sk_X509_CRL_free(crls);
1993 return NULL;
1994 }
1995 sk_X509_CRL_push(crls, crl);
1996 /* Try to download delta CRL */
1997 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1998 crl = load_crl_crldp(crldp);
1999 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2000 if (crl)
2001 sk_X509_CRL_push(crls, crl);
2002 return crls;
2003 }
2004
2005 void store_setup_crl_download(X509_STORE *st)
2006 {
2007 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2008 }
2009
2010 #ifndef OPENSSL_NO_SOCK
2011 static const char *tls_error_hint(void)
2012 {
2013 unsigned long err = ERR_peek_error();
2014
2015 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2016 err = ERR_peek_last_error();
2017 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2018 return NULL;
2019
2020 switch (ERR_GET_REASON(err)) {
2021 case SSL_R_WRONG_VERSION_NUMBER:
2022 return "The server does not support (a suitable version of) TLS";
2023 case SSL_R_UNKNOWN_PROTOCOL:
2024 return "The server does not support HTTPS";
2025 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2026 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2027 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2028 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2029 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2030 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2031 default: /* no error or no hint available for error */
2032 return NULL;
2033 }
2034 }
2035
2036 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2037 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2038 {
2039 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2040 SSL_CTX *ssl_ctx = info->ssl_ctx;
2041 SSL *ssl;
2042 BIO *sbio = NULL;
2043
2044 if (connect && detail) { /* connecting with TLS */
2045 if ((info->use_proxy
2046 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2047 NULL, NULL, /* no proxy credentials */
2048 info->timeout, bio_err, opt_getprog()))
2049 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2050 return NULL;
2051 }
2052 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2053 BIO_free(sbio);
2054 return NULL;
2055 }
2056
2057 SSL_set_tlsext_host_name(ssl, info->server);
2058
2059 SSL_set_connect_state(ssl);
2060 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2061
2062 hbio = BIO_push(sbio, hbio);
2063 } else if (!connect && !detail) { /* disconnecting after error */
2064 const char *hint = tls_error_hint();
2065 if (hint != NULL)
2066 ERR_add_error_data(2, " : ", hint);
2067 /*
2068 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2069 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2070 */
2071 }
2072 return hbio;
2073 }
2074
2075 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2076 const char *no_proxy, SSL_CTX *ssl_ctx,
2077 const STACK_OF(CONF_VALUE) *headers,
2078 long timeout, const char *expected_content_type,
2079 const ASN1_ITEM *it)
2080 {
2081 APP_HTTP_TLS_INFO info;
2082 char *server;
2083 char *port;
2084 int use_ssl;
2085 ASN1_VALUE *resp = NULL;
2086
2087 if (url == NULL || it == NULL) {
2088 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2089 return NULL;
2090 }
2091
2092 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL, NULL, &use_ssl))
2093 return NULL;
2094 if (use_ssl && ssl_ctx == NULL) {
2095 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2096 ERR_add_error_data(1, "missing SSL_CTX");
2097 goto end;
2098 }
2099
2100 info.server = server;
2101 info.port = port;
2102 info.use_proxy = proxy != NULL;
2103 info.timeout = timeout;
2104 info.ssl_ctx = ssl_ctx;
2105 resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2106 NULL, NULL, app_http_tls_cb, &info,
2107 headers, 0 /* maxline */, 0 /* max_resp_len */,
2108 timeout, expected_content_type, it);
2109 end:
2110 OPENSSL_free(server);
2111 OPENSSL_free(port);
2112 return resp;
2113
2114 }
2115
2116 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2117 const char *path, const char *proxy,
2118 const char *no_proxy, SSL_CTX *ssl_ctx,
2119 const STACK_OF(CONF_VALUE) *headers,
2120 const char *content_type,
2121 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2122 long timeout, const ASN1_ITEM *rsp_it)
2123 {
2124 APP_HTTP_TLS_INFO info;
2125
2126 info.server = host;
2127 info.port = port;
2128 info.use_proxy = proxy != NULL;
2129 info.timeout = timeout;
2130 info.ssl_ctx = ssl_ctx;
2131 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2132 proxy, no_proxy,
2133 NULL, NULL, app_http_tls_cb, &info,
2134 headers, content_type, req, req_it,
2135 0 /* maxline */,
2136 0 /* max_resp_len */, timeout, NULL, rsp_it);
2137 }
2138
2139 #endif
2140
2141 /*
2142 * Platform-specific sections
2143 */
2144 #if defined(_WIN32)
2145 # ifdef fileno
2146 # undef fileno
2147 # define fileno(a) (int)_fileno(a)
2148 # endif
2149
2150 # include <windows.h>
2151 # include <tchar.h>
2152
2153 static int WIN32_rename(const char *from, const char *to)
2154 {
2155 TCHAR *tfrom = NULL, *tto;
2156 DWORD err;
2157 int ret = 0;
2158
2159 if (sizeof(TCHAR) == 1) {
2160 tfrom = (TCHAR *)from;
2161 tto = (TCHAR *)to;
2162 } else { /* UNICODE path */
2163
2164 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2165 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2166 if (tfrom == NULL)
2167 goto err;
2168 tto = tfrom + flen;
2169 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2170 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2171 # endif
2172 for (i = 0; i < flen; i++)
2173 tfrom[i] = (TCHAR)from[i];
2174 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2175 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2176 # endif
2177 for (i = 0; i < tlen; i++)
2178 tto[i] = (TCHAR)to[i];
2179 }
2180
2181 if (MoveFile(tfrom, tto))
2182 goto ok;
2183 err = GetLastError();
2184 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2185 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2186 goto ok;
2187 err = GetLastError();
2188 }
2189 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2190 errno = ENOENT;
2191 else if (err == ERROR_ACCESS_DENIED)
2192 errno = EACCES;
2193 else
2194 errno = EINVAL; /* we could map more codes... */
2195 err:
2196 ret = -1;
2197 ok:
2198 if (tfrom != NULL && tfrom != (TCHAR *)from)
2199 free(tfrom);
2200 return ret;
2201 }
2202 #endif
2203
2204 /* app_tminterval section */
2205 #if defined(_WIN32)
2206 double app_tminterval(int stop, int usertime)
2207 {
2208 FILETIME now;
2209 double ret = 0;
2210 static ULARGE_INTEGER tmstart;
2211 static int warning = 1;
2212 # ifdef _WIN32_WINNT
2213 static HANDLE proc = NULL;
2214
2215 if (proc == NULL) {
2216 if (check_winnt())
2217 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2218 GetCurrentProcessId());
2219 if (proc == NULL)
2220 proc = (HANDLE) - 1;
2221 }
2222
2223 if (usertime && proc != (HANDLE) - 1) {
2224 FILETIME junk;
2225 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2226 } else
2227 # endif
2228 {
2229 SYSTEMTIME systime;
2230
2231 if (usertime && warning) {
2232 BIO_printf(bio_err, "To get meaningful results, run "
2233 "this program on idle system.\n");
2234 warning = 0;
2235 }
2236 GetSystemTime(&systime);
2237 SystemTimeToFileTime(&systime, &now);
2238 }
2239
2240 if (stop == TM_START) {
2241 tmstart.u.LowPart = now.dwLowDateTime;
2242 tmstart.u.HighPart = now.dwHighDateTime;
2243 } else {
2244 ULARGE_INTEGER tmstop;
2245
2246 tmstop.u.LowPart = now.dwLowDateTime;
2247 tmstop.u.HighPart = now.dwHighDateTime;
2248
2249 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2250 }
2251
2252 return ret;
2253 }
2254 #elif defined(OPENSSL_SYS_VXWORKS)
2255 # include <time.h>
2256
2257 double app_tminterval(int stop, int usertime)
2258 {
2259 double ret = 0;
2260 # ifdef CLOCK_REALTIME
2261 static struct timespec tmstart;
2262 struct timespec now;
2263 # else
2264 static unsigned long tmstart;
2265 unsigned long now;
2266 # endif
2267 static int warning = 1;
2268
2269 if (usertime && warning) {
2270 BIO_printf(bio_err, "To get meaningful results, run "
2271 "this program on idle system.\n");
2272 warning = 0;
2273 }
2274 # ifdef CLOCK_REALTIME
2275 clock_gettime(CLOCK_REALTIME, &now);
2276 if (stop == TM_START)
2277 tmstart = now;
2278 else
2279 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2280 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2281 # else
2282 now = tickGet();
2283 if (stop == TM_START)
2284 tmstart = now;
2285 else
2286 ret = (now - tmstart) / (double)sysClkRateGet();
2287 # endif
2288 return ret;
2289 }
2290
2291 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2292 # include <sys/times.h>
2293
2294 double app_tminterval(int stop, int usertime)
2295 {
2296 double ret = 0;
2297 struct tms rus;
2298 clock_t now = times(&rus);
2299 static clock_t tmstart;
2300
2301 if (usertime)
2302 now = rus.tms_utime;
2303
2304 if (stop == TM_START) {
2305 tmstart = now;
2306 } else {
2307 long int tck = sysconf(_SC_CLK_TCK);
2308 ret = (now - tmstart) / (double)tck;
2309 }
2310
2311 return ret;
2312 }
2313
2314 #else
2315 # include <sys/time.h>
2316 # include <sys/resource.h>
2317
2318 double app_tminterval(int stop, int usertime)
2319 {
2320 double ret = 0;
2321 struct rusage rus;
2322 struct timeval now;
2323 static struct timeval tmstart;
2324
2325 if (usertime)
2326 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2327 else
2328 gettimeofday(&now, NULL);
2329
2330 if (stop == TM_START)
2331 tmstart = now;
2332 else
2333 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2334 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2335
2336 return ret;
2337 }
2338 #endif
2339
2340 int app_access(const char* name, int flag)
2341 {
2342 #ifdef _WIN32
2343 return _access(name, flag);
2344 #else
2345 return access(name, flag);
2346 #endif
2347 }
2348
2349 int app_isdir(const char *name)
2350 {
2351 return opt_isdir(name);
2352 }
2353
2354 /* raw_read|write section */
2355 #if defined(__VMS)
2356 # include "vms_term_sock.h"
2357 static int stdin_sock = -1;
2358
2359 static void close_stdin_sock(void)
2360 {
2361 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2362 }
2363
2364 int fileno_stdin(void)
2365 {
2366 if (stdin_sock == -1) {
2367 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2368 atexit(close_stdin_sock);
2369 }
2370
2371 return stdin_sock;
2372 }
2373 #else
2374 int fileno_stdin(void)
2375 {
2376 return fileno(stdin);
2377 }
2378 #endif
2379
2380 int fileno_stdout(void)
2381 {
2382 return fileno(stdout);
2383 }
2384
2385 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2386 int raw_read_stdin(void *buf, int siz)
2387 {
2388 DWORD n;
2389 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2390 return n;
2391 else
2392 return -1;
2393 }
2394 #elif defined(__VMS)
2395 # include <sys/socket.h>
2396
2397 int raw_read_stdin(void *buf, int siz)
2398 {
2399 return recv(fileno_stdin(), buf, siz, 0);
2400 }
2401 #else
2402 int raw_read_stdin(void *buf, int siz)
2403 {
2404 return read(fileno_stdin(), buf, siz);
2405 }
2406 #endif
2407
2408 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2409 int raw_write_stdout(const void *buf, int siz)
2410 {
2411 DWORD n;
2412 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2413 return n;
2414 else
2415 return -1;
2416 }
2417 #else
2418 int raw_write_stdout(const void *buf, int siz)
2419 {
2420 return write(fileno_stdout(), buf, siz);
2421 }
2422 #endif
2423
2424 /*
2425 * Centralized handling of input and output files with format specification
2426 * The format is meant to show what the input and output is supposed to be,
2427 * and is therefore a show of intent more than anything else. However, it
2428 * does impact behavior on some platforms, such as differentiating between
2429 * text and binary input/output on non-Unix platforms
2430 */
2431 BIO *dup_bio_in(int format)
2432 {
2433 return BIO_new_fp(stdin,
2434 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2435 }
2436
2437 BIO *dup_bio_out(int format)
2438 {
2439 BIO *b = BIO_new_fp(stdout,
2440 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2441 void *prefix = NULL;
2442
2443 #ifdef OPENSSL_SYS_VMS
2444 if (FMT_istext(format))
2445 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2446 #endif
2447
2448 if (FMT_istext(format)
2449 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2450 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2451 BIO_set_prefix(b, prefix);
2452 }
2453
2454 return b;
2455 }
2456
2457 BIO *dup_bio_err(int format)
2458 {
2459 BIO *b = BIO_new_fp(stderr,
2460 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2461 #ifdef OPENSSL_SYS_VMS
2462 if (FMT_istext(format))
2463 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2464 #endif
2465 return b;
2466 }
2467
2468 void unbuffer(FILE *fp)
2469 {
2470 /*
2471 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2472 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2473 * However, we trust that the C RTL will never give us a FILE pointer
2474 * above the first 4 GB of memory, so we simply turn off the warning
2475 * temporarily.
2476 */
2477 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2478 # pragma environment save
2479 # pragma message disable maylosedata2
2480 #endif
2481 setbuf(fp, NULL);
2482 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2483 # pragma environment restore
2484 #endif
2485 }
2486
2487 static const char *modestr(char mode, int format)
2488 {
2489 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2490
2491 switch (mode) {
2492 case 'a':
2493 return FMT_istext(format) ? "a" : "ab";
2494 case 'r':
2495 return FMT_istext(format) ? "r" : "rb";
2496 case 'w':
2497 return FMT_istext(format) ? "w" : "wb";
2498 }
2499 /* The assert above should make sure we never reach this point */
2500 return NULL;
2501 }
2502
2503 static const char *modeverb(char mode)
2504 {
2505 switch (mode) {
2506 case 'a':
2507 return "appending";
2508 case 'r':
2509 return "reading";
2510 case 'w':
2511 return "writing";
2512 }
2513 return "(doing something)";
2514 }
2515
2516 /*
2517 * Open a file for writing, owner-read-only.
2518 */
2519 BIO *bio_open_owner(const char *filename, int format, int private)
2520 {
2521 FILE *fp = NULL;
2522 BIO *b = NULL;
2523 int fd = -1, bflags, mode, textmode;
2524
2525 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2526 return bio_open_default(filename, 'w', format);
2527
2528 mode = O_WRONLY;
2529 #ifdef O_CREAT
2530 mode |= O_CREAT;
2531 #endif
2532 #ifdef O_TRUNC
2533 mode |= O_TRUNC;
2534 #endif
2535 textmode = FMT_istext(format);
2536 if (!textmode) {
2537 #ifdef O_BINARY
2538 mode |= O_BINARY;
2539 #elif defined(_O_BINARY)
2540 mode |= _O_BINARY;
2541 #endif
2542 }
2543
2544 #ifdef OPENSSL_SYS_VMS
2545 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2546 * it still needs to know that we're going binary, or fdopen()
2547 * will fail with "invalid argument"... so we tell VMS what the
2548 * context is.
2549 */
2550 if (!textmode)
2551 fd = open(filename, mode, 0600, "ctx=bin");
2552 else
2553 #endif
2554 fd = open(filename, mode, 0600);
2555 if (fd < 0)
2556 goto err;
2557 fp = fdopen(fd, modestr('w', format));
2558 if (fp == NULL)
2559 goto err;
2560 bflags = BIO_CLOSE;
2561 if (textmode)
2562 bflags |= BIO_FP_TEXT;
2563 b = BIO_new_fp(fp, bflags);
2564 if (b)
2565 return b;
2566
2567 err:
2568 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2569 opt_getprog(), filename, strerror(errno));
2570 ERR_print_errors(bio_err);
2571 /* If we have fp, then fdopen took over fd, so don't close both. */
2572 if (fp)
2573 fclose(fp);
2574 else if (fd >= 0)
2575 close(fd);
2576 return NULL;
2577 }
2578
2579 static BIO *bio_open_default_(const char *filename, char mode, int format,
2580 int quiet)
2581 {
2582 BIO *ret;
2583
2584 if (filename == NULL || strcmp(filename, "-") == 0) {
2585 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2586 if (quiet) {
2587 ERR_clear_error();
2588 return ret;
2589 }
2590 if (ret != NULL)
2591 return ret;
2592 BIO_printf(bio_err,
2593 "Can't open %s, %s\n",
2594 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2595 } else {
2596 ret = BIO_new_file(filename, modestr(mode, format));
2597 if (quiet) {
2598 ERR_clear_error();
2599 return ret;
2600 }
2601 if (ret != NULL)
2602 return ret;
2603 BIO_printf(bio_err,
2604 "Can't open %s for %s, %s\n",
2605 filename, modeverb(mode), strerror(errno));
2606 }
2607 ERR_print_errors(bio_err);
2608 return NULL;
2609 }
2610
2611 BIO *bio_open_default(const char *filename, char mode, int format)
2612 {
2613 return bio_open_default_(filename, mode, format, 0);
2614 }
2615
2616 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2617 {
2618 return bio_open_default_(filename, mode, format, 1);
2619 }
2620
2621 void wait_for_async(SSL *s)
2622 {
2623 /* On Windows select only works for sockets, so we simply don't wait */
2624 #ifndef OPENSSL_SYS_WINDOWS
2625 int width = 0;
2626 fd_set asyncfds;
2627 OSSL_ASYNC_FD *fds;
2628 size_t numfds;
2629 size_t i;
2630
2631 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2632 return;
2633 if (numfds == 0)
2634 return;
2635 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2636 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2637 OPENSSL_free(fds);
2638 return;
2639 }
2640
2641 FD_ZERO(&asyncfds);
2642 for (i = 0; i < numfds; i++) {
2643 if (width <= (int)fds[i])
2644 width = (int)fds[i] + 1;
2645 openssl_fdset((int)fds[i], &asyncfds);
2646 }
2647 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2648 OPENSSL_free(fds);
2649 #endif
2650 }
2651
2652 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2653 #if defined(OPENSSL_SYS_MSDOS)
2654 int has_stdin_waiting(void)
2655 {
2656 # if defined(OPENSSL_SYS_WINDOWS)
2657 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2658 DWORD events = 0;
2659 INPUT_RECORD inputrec;
2660 DWORD insize = 1;
2661 BOOL peeked;
2662
2663 if (inhand == INVALID_HANDLE_VALUE) {
2664 return 0;
2665 }
2666
2667 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2668 if (!peeked) {
2669 /* Probably redirected input? _kbhit() does not work in this case */
2670 if (!feof(stdin)) {
2671 return 1;
2672 }
2673 return 0;
2674 }
2675 # endif
2676 return _kbhit();
2677 }
2678 #endif
2679
2680 /* Corrupt a signature by modifying final byte */
2681 void corrupt_signature(const ASN1_STRING *signature)
2682 {
2683 unsigned char *s = signature->data;
2684 s[signature->length - 1] ^= 0x1;
2685 }
2686
2687 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2688 int days)
2689 {
2690 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2691 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2692 return 0;
2693 } else {
2694 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2695 return 0;
2696 }
2697 if (enddate == NULL) {
2698 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2699 == NULL)
2700 return 0;
2701 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2702 return 0;
2703 }
2704 return 1;
2705 }
2706
2707 void make_uppercase(char *string)
2708 {
2709 int i;
2710
2711 for (i = 0; string[i] != '\0'; i++)
2712 string[i] = toupper((unsigned char)string[i]);
2713 }
2714
2715 int opt_printf_stderr(const char *fmt, ...)
2716 {
2717 va_list ap;
2718 int ret;
2719
2720 va_start(ap, fmt);
2721 ret = BIO_vprintf(bio_err, fmt, ap);
2722 va_end(ap);
2723 return ret;
2724 }
2725
2726 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2727 const OSSL_PARAM *paramdefs)
2728 {
2729 OSSL_PARAM *params = NULL;
2730 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2731 size_t params_n;
2732 char *opt = "", *stmp, *vtmp = NULL;
2733 int found = 1;
2734
2735 if (opts == NULL)
2736 return NULL;
2737
2738 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2739 if (params == NULL)
2740 return NULL;
2741
2742 for (params_n = 0; params_n < sz; params_n++) {
2743 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2744 if ((stmp = OPENSSL_strdup(opt)) == NULL
2745 || (vtmp = strchr(stmp, ':')) == NULL)
2746 goto err;
2747 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2748 *vtmp = 0;
2749 /* Skip over the separator so that vmtp points to the value */
2750 vtmp++;
2751 if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
2752 stmp, vtmp, strlen(vtmp), &found))
2753 goto err;
2754 OPENSSL_free(stmp);
2755 }
2756 params[params_n] = OSSL_PARAM_construct_end();
2757 return params;
2758 err:
2759 OPENSSL_free(stmp);
2760 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2761 opt);
2762 ERR_print_errors(bio_err);
2763 app_params_free(params);
2764 return NULL;
2765 }
2766
2767 void app_params_free(OSSL_PARAM *params)
2768 {
2769 int i;
2770
2771 if (params != NULL) {
2772 for (i = 0; params[i].key != NULL; ++i)
2773 OPENSSL_free(params[i].data);
2774 OPENSSL_free(params);
2775 }
2776 }