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