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