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