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