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