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