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