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