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