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