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