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