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