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