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