Have a shared library version thats reasonable with our version scheme
[openssl.git] / apps / apps.c
1 /* apps/apps.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
113 /*
114  * On VMS, you need to define this to get the declaration of fileno().  The
115  * value 2 is to make sure no function defined in POSIX-2 is left undefined.
116  */
117 # define _POSIX_C_SOURCE 2
118 #endif
119 #include <stdio.h>
120 #include <stdlib.h>
121 #include <string.h>
122 #if !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_WINCE) && !defined(NETWARE_CLIB)
123 # include <strings.h>
124 #endif
125 #include <sys/types.h>
126 #include <ctype.h>
127 #include <errno.h>
128 #include <assert.h>
129 #include <openssl/err.h>
130 #include <openssl/x509.h>
131 #include <openssl/x509v3.h>
132 #include <openssl/pem.h>
133 #include <openssl/pkcs12.h>
134 #include <openssl/ui.h>
135 #include <openssl/safestack.h>
136 #ifndef OPENSSL_NO_ENGINE
137 # include <openssl/engine.h>
138 #endif
139 #ifndef OPENSSL_NO_RSA
140 # include <openssl/rsa.h>
141 #endif
142 #include <openssl/bn.h>
143 #ifndef OPENSSL_NO_JPAKE
144 # include <openssl/jpake.h>
145 #endif
146
147 #define NON_MAIN
148 #include "apps.h"
149 #undef NON_MAIN
150
151 #ifdef _WIN32
152 static int WIN32_rename(const char *from, const char *to);
153 # define rename(from,to) WIN32_rename((from),(to))
154 #endif
155
156 typedef struct {
157     const char *name;
158     unsigned long flag;
159     unsigned long mask;
160 } NAME_EX_TBL;
161
162 static UI_METHOD *ui_method = NULL;
163
164 static int set_table_opts(unsigned long *flags, const char *arg,
165                           const NAME_EX_TBL * in_tbl);
166 static int set_multi_opts(unsigned long *flags, const char *arg,
167                           const NAME_EX_TBL * in_tbl);
168
169 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
170 /* Looks like this stuff is worth moving into separate function */
171 static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
172                                    const char *key_descrip, int format);
173 #endif
174
175 int app_init(long mesgwin);
176 #ifdef undef                    /* never finished - probably never will be
177                                  * :-) */
178 int args_from_file(char *file, int *argc, char **argv[])
179 {
180     FILE *fp;
181     int num, i;
182     unsigned int len;
183     static char *buf = NULL;
184     static char **arg = NULL;
185     char *p;
186
187     fp = fopen(file, "r");
188     if (fp == NULL)
189         return (0);
190
191     if (fseek(fp, 0, SEEK_END) == 0)
192         len = ftell(fp), rewind(fp);
193     else
194         len = -1;
195     if (len <= 0) {
196         fclose(fp);
197         return (0);
198     }
199
200     *argc = 0;
201     *argv = NULL;
202
203     if (buf != NULL)
204         OPENSSL_free(buf);
205     buf = (char *)OPENSSL_malloc(len + 1);
206     if (buf == NULL)
207         return (0);
208
209     len = fread(buf, 1, len, fp);
210     if (len <= 1)
211         return (0);
212     buf[len] = '\0';
213
214     i = 0;
215     for (p = buf; *p; p++)
216         if (*p == '\n')
217             i++;
218     if (arg != NULL)
219         OPENSSL_free(arg);
220     arg = (char **)OPENSSL_malloc(sizeof(char *) * (i * 2));
221
222     *argv = arg;
223     num = 0;
224     p = buf;
225     for (;;) {
226         if (!*p)
227             break;
228         if (*p == '#') {        /* comment line */
229             while (*p && (*p != '\n'))
230                 p++;
231             continue;
232         }
233         /* else we have a line */
234         *(arg++) = p;
235         num++;
236         while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
237             p++;
238         if (!*p)
239             break;
240         if (*p == '\n') {
241             *(p++) = '\0';
242             continue;
243         }
244         /* else it is a tab or space */
245         p++;
246         while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
247             p++;
248         if (!*p)
249             break;
250         if (*p == '\n') {
251             p++;
252             continue;
253         }
254         *(arg++) = p++;
255         num++;
256         while (*p && (*p != '\n'))
257             p++;
258         if (!*p)
259             break;
260         /* else *p == '\n' */
261         *(p++) = '\0';
262     }
263     *argc = num;
264     return (1);
265 }
266 #endif
267
268 int str2fmt(char *s)
269 {
270     if (s == NULL)
271         return FORMAT_UNDEF;
272     if ((*s == 'D') || (*s == 'd'))
273         return (FORMAT_ASN1);
274     else if ((*s == 'T') || (*s == 't'))
275         return (FORMAT_TEXT);
276     else if ((strcmp(s, "NSS") == 0) || (strcmp(s, "nss") == 0))
277         return (FORMAT_NSS);
278     else if ((*s == 'N') || (*s == 'n'))
279         return (FORMAT_NETSCAPE);
280     else if ((*s == 'S') || (*s == 's'))
281         return (FORMAT_SMIME);
282     else if ((*s == 'M') || (*s == 'm'))
283         return (FORMAT_MSBLOB);
284     else if ((*s == '1')
285              || (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0)
286              || (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
287         return (FORMAT_PKCS12);
288     else if ((*s == 'E') || (*s == 'e'))
289         return (FORMAT_ENGINE);
290     else if ((*s == 'H') || (*s == 'h'))
291         return FORMAT_HTTP;
292     else if ((*s == 'P') || (*s == 'p')) {
293         if (s[1] == 'V' || s[1] == 'v')
294             return FORMAT_PVK;
295         else
296             return (FORMAT_PEM);
297     } else
298         return (FORMAT_UNDEF);
299 }
300
301 #if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_NETWARE)
302 void program_name(char *in, char *out, int size)
303 {
304     int i, n;
305     char *p = NULL;
306
307     n = strlen(in);
308     /* find the last '/', '\' or ':' */
309     for (i = n - 1; i > 0; i--) {
310         if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':')) {
311             p = &(in[i + 1]);
312             break;
313         }
314     }
315     if (p == NULL)
316         p = in;
317     n = strlen(p);
318
319 # if defined(OPENSSL_SYS_NETWARE)
320     /* strip off trailing .nlm if present. */
321     if ((n > 4) && (p[n - 4] == '.') &&
322         ((p[n - 3] == 'n') || (p[n - 3] == 'N')) &&
323         ((p[n - 2] == 'l') || (p[n - 2] == 'L')) &&
324         ((p[n - 1] == 'm') || (p[n - 1] == 'M')))
325         n -= 4;
326 # else
327     /* strip off trailing .exe if present. */
328     if ((n > 4) && (p[n - 4] == '.') &&
329         ((p[n - 3] == 'e') || (p[n - 3] == 'E')) &&
330         ((p[n - 2] == 'x') || (p[n - 2] == 'X')) &&
331         ((p[n - 1] == 'e') || (p[n - 1] == 'E')))
332         n -= 4;
333 # endif
334
335     if (n > size - 1)
336         n = size - 1;
337
338     for (i = 0; i < n; i++) {
339         if ((p[i] >= 'A') && (p[i] <= 'Z'))
340             out[i] = p[i] - 'A' + 'a';
341         else
342             out[i] = p[i];
343     }
344     out[n] = '\0';
345 }
346 #else
347 # ifdef OPENSSL_SYS_VMS
348 void program_name(char *in, char *out, int size)
349 {
350     char *p = in, *q;
351     char *chars = ":]>";
352
353     while (*chars != '\0') {
354         q = strrchr(p, *chars);
355         if (q > p)
356             p = q + 1;
357         chars++;
358     }
359
360     q = strrchr(p, '.');
361     if (q == NULL)
362         q = p + strlen(p);
363     strncpy(out, p, size - 1);
364     if (q - p >= size) {
365         out[size - 1] = '\0';
366     } else {
367         out[q - p] = '\0';
368     }
369 }
370 # else
371 void program_name(char *in, char *out, int size)
372 {
373     char *p;
374
375     p = strrchr(in, '/');
376     if (p != NULL)
377         p++;
378     else
379         p = in;
380     BUF_strlcpy(out, p, size);
381 }
382 # endif
383 #endif
384
385 int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
386 {
387     int num, i;
388     char *p;
389
390     *argc = 0;
391     *argv = NULL;
392
393     i = 0;
394     if (arg->count == 0) {
395         arg->count = 20;
396         arg->data = (char **)OPENSSL_malloc(sizeof(char *) * arg->count);
397         if (arg->data == NULL)
398             return 0;
399     }
400     for (i = 0; i < arg->count; i++)
401         arg->data[i] = NULL;
402
403     num = 0;
404     p = buf;
405     for (;;) {
406         /* first scan over white space */
407         if (!*p)
408             break;
409         while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
410             p++;
411         if (!*p)
412             break;
413
414         /* The start of something good :-) */
415         if (num >= arg->count) {
416             char **tmp_p;
417             int tlen = arg->count + 20;
418             tmp_p = (char **)OPENSSL_realloc(arg->data,
419                                              sizeof(char *) * tlen);
420             if (tmp_p == NULL)
421                 return 0;
422             arg->data = tmp_p;
423             arg->count = tlen;
424             /* initialize newly allocated data */
425             for (i = num; i < arg->count; i++)
426                 arg->data[i] = NULL;
427         }
428         arg->data[num++] = p;
429
430         /* now look for the end of this */
431         if ((*p == '\'') || (*p == '\"')) { /* scan for closing quote */
432             i = *(p++);
433             arg->data[num - 1]++; /* jump over quote */
434             while (*p && (*p != i))
435                 p++;
436             *p = '\0';
437         } else {
438             while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
439                 p++;
440
441             if (*p == '\0')
442                 p--;
443             else
444                 *p = '\0';
445         }
446         p++;
447     }
448     *argc = num;
449     *argv = arg->data;
450     return (1);
451 }
452
453 #ifndef APP_INIT
454 int app_init(long mesgwin)
455 {
456     return (1);
457 }
458 #endif
459
460 int dump_cert_text(BIO *out, X509 *x)
461 {
462     char *p;
463
464     p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
465     BIO_puts(out, "subject=");
466     BIO_puts(out, p);
467     OPENSSL_free(p);
468
469     p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
470     BIO_puts(out, "\nissuer=");
471     BIO_puts(out, p);
472     BIO_puts(out, "\n");
473     OPENSSL_free(p);
474
475     return 0;
476 }
477
478 static int ui_open(UI *ui)
479 {
480     return UI_method_get_opener(UI_OpenSSL())(ui);
481 }
482
483 static int ui_read(UI *ui, UI_STRING *uis)
484 {
485     if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
486         && UI_get0_user_data(ui)) {
487         switch (UI_get_string_type(uis)) {
488         case UIT_PROMPT:
489         case UIT_VERIFY:
490             {
491                 const char *password =
492                     ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
493                 if (password && password[0] != '\0') {
494                     UI_set_result(ui, uis, password);
495                     return 1;
496                 }
497             }
498         default:
499             break;
500         }
501     }
502     return UI_method_get_reader(UI_OpenSSL())(ui, uis);
503 }
504
505 static int ui_write(UI *ui, UI_STRING *uis)
506 {
507     if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
508         && UI_get0_user_data(ui)) {
509         switch (UI_get_string_type(uis)) {
510         case UIT_PROMPT:
511         case UIT_VERIFY:
512             {
513                 const char *password =
514                     ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
515                 if (password && password[0] != '\0')
516                     return 1;
517             }
518         default:
519             break;
520         }
521     }
522     return UI_method_get_writer(UI_OpenSSL())(ui, uis);
523 }
524
525 static int ui_close(UI *ui)
526 {
527     return UI_method_get_closer(UI_OpenSSL())(ui);
528 }
529
530 int setup_ui_method(void)
531 {
532     ui_method = UI_create_method("OpenSSL application user interface");
533     UI_method_set_opener(ui_method, ui_open);
534     UI_method_set_reader(ui_method, ui_read);
535     UI_method_set_writer(ui_method, ui_write);
536     UI_method_set_closer(ui_method, ui_close);
537     return 0;
538 }
539
540 void destroy_ui_method(void)
541 {
542     if (ui_method) {
543         UI_destroy_method(ui_method);
544         ui_method = NULL;
545     }
546 }
547
548 int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
549 {
550     UI *ui = NULL;
551     int res = 0;
552     const char *prompt_info = NULL;
553     const char *password = NULL;
554     PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
555
556     if (cb_data) {
557         if (cb_data->password)
558             password = cb_data->password;
559         if (cb_data->prompt_info)
560             prompt_info = cb_data->prompt_info;
561     }
562
563     if (password) {
564         res = strlen(password);
565         if (res > bufsiz)
566             res = bufsiz;
567         memcpy(buf, password, res);
568         return res;
569     }
570
571     ui = UI_new_method(ui_method);
572     if (ui) {
573         int ok = 0;
574         char *buff = NULL;
575         int ui_flags = 0;
576         char *prompt = NULL;
577
578         prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
579         if(!prompt) {
580             BIO_printf(bio_err, "Out of memory\n");
581             UI_free(ui);
582             return 0;
583         }
584
585         ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
586         UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
587
588         if (ok >= 0)
589             ok = UI_add_input_string(ui, prompt, ui_flags, buf,
590                                      PW_MIN_LENGTH, bufsiz - 1);
591         if (ok >= 0 && verify) {
592             buff = (char *)OPENSSL_malloc(bufsiz);
593             if(!buff) {
594                 BIO_printf(bio_err, "Out of memory\n");
595                 UI_free(ui);
596                 OPENSSL_free(prompt);
597                 return 0;
598             }
599             ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
600                                       PW_MIN_LENGTH, bufsiz - 1, buf);
601         }
602         if (ok >= 0)
603             do {
604                 ok = UI_process(ui);
605             }
606             while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
607
608         if (buff) {
609             OPENSSL_cleanse(buff, (unsigned int)bufsiz);
610             OPENSSL_free(buff);
611         }
612
613         if (ok >= 0)
614             res = strlen(buf);
615         if (ok == -1) {
616             BIO_printf(bio_err, "User interface error\n");
617             ERR_print_errors(bio_err);
618             OPENSSL_cleanse(buf, (unsigned int)bufsiz);
619             res = 0;
620         }
621         if (ok == -2) {
622             BIO_printf(bio_err, "aborted!\n");
623             OPENSSL_cleanse(buf, (unsigned int)bufsiz);
624             res = 0;
625         }
626         UI_free(ui);
627         OPENSSL_free(prompt);
628     }
629     return res;
630 }
631
632 static char *app_get_pass(BIO *err, char *arg, int keepbio);
633
634 int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
635 {
636     int same;
637     if (!arg2 || !arg1 || strcmp(arg1, arg2))
638         same = 0;
639     else
640         same = 1;
641     if (arg1) {
642         *pass1 = app_get_pass(err, arg1, same);
643         if (!*pass1)
644             return 0;
645     } else if (pass1)
646         *pass1 = NULL;
647     if (arg2) {
648         *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
649         if (!*pass2)
650             return 0;
651     } else if (pass2)
652         *pass2 = NULL;
653     return 1;
654 }
655
656 static char *app_get_pass(BIO *err, char *arg, int keepbio)
657 {
658     char *tmp, tpass[APP_PASS_LEN];
659     static BIO *pwdbio = NULL;
660     int i;
661     if (!strncmp(arg, "pass:", 5))
662         return BUF_strdup(arg + 5);
663     if (!strncmp(arg, "env:", 4)) {
664         tmp = getenv(arg + 4);
665         if (!tmp) {
666             BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
667             return NULL;
668         }
669         return BUF_strdup(tmp);
670     }
671     if (!keepbio || !pwdbio) {
672         if (!strncmp(arg, "file:", 5)) {
673             pwdbio = BIO_new_file(arg + 5, "r");
674             if (!pwdbio) {
675                 BIO_printf(err, "Can't open file %s\n", arg + 5);
676                 return NULL;
677             }
678 #if !defined(_WIN32)
679             /*
680              * Under _WIN32, which covers even Win64 and CE, file
681              * descriptors referenced by BIO_s_fd are not inherited
682              * by child process and therefore below is not an option.
683              * It could have been an option if bss_fd.c was operating
684              * on real Windows descriptors, such as those obtained
685              * with CreateFile.
686              */
687         } else if (!strncmp(arg, "fd:", 3)) {
688             BIO *btmp;
689             i = atoi(arg + 3);
690             if (i >= 0)
691                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
692             if ((i < 0) || !pwdbio) {
693                 BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
694                 return NULL;
695             }
696             /*
697              * Can't do BIO_gets on an fd BIO so add a buffering BIO
698              */
699             btmp = BIO_new(BIO_f_buffer());
700             pwdbio = BIO_push(btmp, pwdbio);
701 #endif
702         } else if (!strcmp(arg, "stdin")) {
703             pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
704             if (!pwdbio) {
705                 BIO_printf(err, "Can't open BIO for stdin\n");
706                 return NULL;
707             }
708         } else {
709             BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
710             return NULL;
711         }
712     }
713     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
714     if (keepbio != 1) {
715         BIO_free_all(pwdbio);
716         pwdbio = NULL;
717     }
718     if (i <= 0) {
719         BIO_printf(err, "Error reading password from BIO\n");
720         return NULL;
721     }
722     tmp = strchr(tpass, '\n');
723     if (tmp)
724         *tmp = 0;
725     return BUF_strdup(tpass);
726 }
727
728 int add_oid_section(BIO *err, CONF *conf)
729 {
730     char *p;
731     STACK_OF(CONF_VALUE) *sktmp;
732     CONF_VALUE *cnf;
733     int i;
734     if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
735         ERR_clear_error();
736         return 1;
737     }
738     if (!(sktmp = NCONF_get_section(conf, p))) {
739         BIO_printf(err, "problem loading oid section %s\n", p);
740         return 0;
741     }
742     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
743         cnf = sk_CONF_VALUE_value(sktmp, i);
744         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
745             BIO_printf(err, "problem creating object %s=%s\n",
746                        cnf->name, cnf->value);
747             return 0;
748         }
749     }
750     return 1;
751 }
752
753 static int load_pkcs12(BIO *err, BIO *in, const char *desc,
754                        pem_password_cb *pem_cb, void *cb_data,
755                        EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
756 {
757     const char *pass;
758     char tpass[PEM_BUFSIZE];
759     int len, ret = 0;
760     PKCS12 *p12;
761     p12 = d2i_PKCS12_bio(in, NULL);
762     if (p12 == NULL) {
763         BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);
764         goto die;
765     }
766     /* See if an empty password will do */
767     if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
768         pass = "";
769     else {
770         if (!pem_cb)
771             pem_cb = (pem_password_cb *)password_callback;
772         len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
773         if (len < 0) {
774             BIO_printf(err, "Passpharse callback error for %s\n", desc);
775             goto die;
776         }
777         if (len < PEM_BUFSIZE)
778             tpass[len] = 0;
779         if (!PKCS12_verify_mac(p12, tpass, len)) {
780             BIO_printf(err,
781                        "Mac verify error (wrong password?) in PKCS12 file for %s\n",
782                        desc);
783             goto die;
784         }
785         pass = tpass;
786     }
787     ret = PKCS12_parse(p12, pass, pkey, cert, ca);
788  die:
789     if (p12)
790         PKCS12_free(p12);
791     return ret;
792 }
793
794 int load_cert_crl_http(const char *url, BIO *err,
795                        X509 **pcert, X509_CRL **pcrl)
796 {
797     char *host = NULL, *port = NULL, *path = NULL;
798     BIO *bio = NULL;
799     OCSP_REQ_CTX *rctx = NULL;
800     int use_ssl, rv = 0;
801     if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
802         goto err;
803     if (use_ssl) {
804         if (err)
805             BIO_puts(err, "https not supported\n");
806         goto err;
807     }
808     bio = BIO_new_connect(host);
809     if (!bio || !BIO_set_conn_port(bio, port))
810         goto err;
811     rctx = OCSP_REQ_CTX_new(bio, 1024);
812     if (!rctx)
813         goto err;
814     if (!OCSP_REQ_CTX_http(rctx, "GET", path))
815         goto err;
816     if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
817         goto err;
818     if (pcert) {
819         do {
820             rv = X509_http_nbio(rctx, pcert);
821         }
822         while (rv == -1);
823     } else {
824         do {
825             rv = X509_CRL_http_nbio(rctx, pcrl);
826         } while (rv == -1);
827     }
828
829  err:
830     if (host)
831         OPENSSL_free(host);
832     if (path)
833         OPENSSL_free(path);
834     if (port)
835         OPENSSL_free(port);
836     if (bio)
837         BIO_free_all(bio);
838     if (rctx)
839         OCSP_REQ_CTX_free(rctx);
840     if (rv != 1) {
841         if (bio && err)
842             BIO_printf(bio_err, "Error loading %s from %s\n",
843                        pcert ? "certificate" : "CRL", url);
844         ERR_print_errors(bio_err);
845     }
846     return rv;
847 }
848
849 X509 *load_cert(BIO *err, const char *file, int format,
850                 const char *pass, ENGINE *e, const char *cert_descrip)
851 {
852     X509 *x = NULL;
853     BIO *cert;
854
855     if (format == FORMAT_HTTP) {
856         load_cert_crl_http(file, err, &x, NULL);
857         return x;
858     }
859
860     if ((cert = BIO_new(BIO_s_file())) == NULL) {
861         ERR_print_errors(err);
862         goto end;
863     }
864
865     if (file == NULL) {
866         setbuf(stdin, NULL); /* don't do buffered reads */
867         BIO_set_fp(cert, stdin, BIO_NOCLOSE);
868     } else {
869         if (BIO_read_filename(cert, file) <= 0) {
870             BIO_printf(err, "Error opening %s %s\n", cert_descrip, file);
871             ERR_print_errors(err);
872             goto end;
873         }
874     }
875
876     if (format == FORMAT_ASN1)
877         x = d2i_X509_bio(cert, NULL);
878     else if (format == FORMAT_NETSCAPE) {
879         NETSCAPE_X509 *nx;
880         nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509), cert, NULL);
881         if (nx == NULL)
882             goto end;
883
884         if ((strncmp(NETSCAPE_CERT_HDR, (char *)nx->header->data,
885                      nx->header->length) != 0)) {
886             NETSCAPE_X509_free(nx);
887             BIO_printf(err, "Error reading header on certificate\n");
888             goto end;
889         }
890         x = nx->cert;
891         nx->cert = NULL;
892         NETSCAPE_X509_free(nx);
893     } else if (format == FORMAT_PEM)
894         x = PEM_read_bio_X509_AUX(cert, NULL,
895                                   (pem_password_cb *)password_callback, NULL);
896     else if (format == FORMAT_PKCS12) {
897         if (!load_pkcs12(err, cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
898             goto end;
899     } else {
900         BIO_printf(err, "bad input format specified for %s\n", cert_descrip);
901         goto end;
902     }
903  end:
904     if (x == NULL) {
905         BIO_printf(err, "unable to load certificate\n");
906         ERR_print_errors(err);
907     }
908     if (cert != NULL)
909         BIO_free(cert);
910     return (x);
911 }
912
913 X509_CRL *load_crl(const char *infile, int format)
914 {
915     X509_CRL *x = NULL;
916     BIO *in = NULL;
917
918     if (format == FORMAT_HTTP) {
919         load_cert_crl_http(infile, bio_err, NULL, &x);
920         return x;
921     }
922
923     in = BIO_new(BIO_s_file());
924     if (in == NULL) {
925         ERR_print_errors(bio_err);
926         goto end;
927     }
928
929     if (infile == NULL)
930         BIO_set_fp(in, stdin, BIO_NOCLOSE);
931     else {
932         if (BIO_read_filename(in, infile) <= 0) {
933             perror(infile);
934             goto end;
935         }
936     }
937     if (format == FORMAT_ASN1)
938         x = d2i_X509_CRL_bio(in, NULL);
939     else if (format == FORMAT_PEM)
940         x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
941     else {
942         BIO_printf(bio_err, "bad input format specified for input crl\n");
943         goto end;
944     }
945     if (x == NULL) {
946         BIO_printf(bio_err, "unable to load CRL\n");
947         ERR_print_errors(bio_err);
948         goto end;
949     }
950
951  end:
952     BIO_free(in);
953     return (x);
954 }
955
956 EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
957                    const char *pass, ENGINE *e, const char *key_descrip)
958 {
959     BIO *key = NULL;
960     EVP_PKEY *pkey = NULL;
961     PW_CB_DATA cb_data;
962
963     cb_data.password = pass;
964     cb_data.prompt_info = file;
965
966     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
967         BIO_printf(err, "no keyfile specified\n");
968         goto end;
969     }
970 #ifndef OPENSSL_NO_ENGINE
971     if (format == FORMAT_ENGINE) {
972         if (!e)
973             BIO_printf(err, "no engine specified\n");
974         else {
975             pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
976             if (!pkey) {
977                 BIO_printf(err, "cannot load %s from engine\n", key_descrip);
978                 ERR_print_errors(err);
979             }
980         }
981         goto end;
982     }
983 #endif
984     key = BIO_new(BIO_s_file());
985     if (key == NULL) {
986         ERR_print_errors(err);
987         goto end;
988     }
989     if (file == NULL && maybe_stdin) {
990         setbuf(stdin, NULL); /* don't do buffered reads */
991         BIO_set_fp(key, stdin, BIO_NOCLOSE);
992     } else if (BIO_read_filename(key, file) <= 0) {
993         BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
994         ERR_print_errors(err);
995         goto end;
996     }
997     if (format == FORMAT_ASN1) {
998         pkey = d2i_PrivateKey_bio(key, NULL);
999     } else if (format == FORMAT_PEM) {
1000         pkey = PEM_read_bio_PrivateKey(key, NULL,
1001                                        (pem_password_cb *)password_callback,
1002                                        &cb_data);
1003     }
1004 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
1005     else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
1006         pkey = load_netscape_key(err, key, file, key_descrip, format);
1007 #endif
1008     else if (format == FORMAT_PKCS12) {
1009         if (!load_pkcs12(err, key, key_descrip,
1010                          (pem_password_cb *)password_callback, &cb_data,
1011                          &pkey, NULL, NULL))
1012             goto end;
1013     }
1014 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
1015     else if (format == FORMAT_MSBLOB)
1016         pkey = b2i_PrivateKey_bio(key);
1017     else if (format == FORMAT_PVK)
1018         pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
1019                            &cb_data);
1020 #endif
1021     else {
1022         BIO_printf(err, "bad input format specified for key file\n");
1023         goto end;
1024     }
1025  end:
1026     if (key != NULL)
1027         BIO_free(key);
1028     if (pkey == NULL) {
1029         BIO_printf(err, "unable to load %s\n", key_descrip);
1030         ERR_print_errors(err);
1031     }
1032     return (pkey);
1033 }
1034
1035 EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
1036                       const char *pass, ENGINE *e, const char *key_descrip)
1037 {
1038     BIO *key = NULL;
1039     EVP_PKEY *pkey = NULL;
1040     PW_CB_DATA cb_data;
1041
1042     cb_data.password = pass;
1043     cb_data.prompt_info = file;
1044
1045     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
1046         BIO_printf(err, "no keyfile specified\n");
1047         goto end;
1048     }
1049 #ifndef OPENSSL_NO_ENGINE
1050     if (format == FORMAT_ENGINE) {
1051         if (!e)
1052             BIO_printf(bio_err, "no engine specified\n");
1053         else
1054             pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
1055         goto end;
1056     }
1057 #endif
1058     key = BIO_new(BIO_s_file());
1059     if (key == NULL) {
1060         ERR_print_errors(err);
1061         goto end;
1062     }
1063     if (file == NULL && maybe_stdin) {
1064         setbuf(stdin, NULL); /* don't do buffered reads */
1065         BIO_set_fp(key, stdin, BIO_NOCLOSE);
1066     } else if (BIO_read_filename(key, file) <= 0) {
1067         BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
1068         ERR_print_errors(err);
1069         goto end;
1070     }
1071     if (format == FORMAT_ASN1) {
1072         pkey = d2i_PUBKEY_bio(key, NULL);
1073     }
1074 #ifndef OPENSSL_NO_RSA
1075     else if (format == FORMAT_ASN1RSA) {
1076         RSA *rsa;
1077         rsa = d2i_RSAPublicKey_bio(key, NULL);
1078         if (rsa) {
1079             pkey = EVP_PKEY_new();
1080             if (pkey)
1081                 EVP_PKEY_set1_RSA(pkey, rsa);
1082             RSA_free(rsa);
1083         } else
1084             pkey = NULL;
1085     } else if (format == FORMAT_PEMRSA) {
1086         RSA *rsa;
1087         rsa = PEM_read_bio_RSAPublicKey(key, NULL,
1088                                         (pem_password_cb *)password_callback,
1089                                         &cb_data);
1090         if (rsa) {
1091             pkey = EVP_PKEY_new();
1092             if (pkey)
1093                 EVP_PKEY_set1_RSA(pkey, rsa);
1094             RSA_free(rsa);
1095         } else
1096             pkey = NULL;
1097     }
1098 #endif
1099     else if (format == FORMAT_PEM) {
1100         pkey = PEM_read_bio_PUBKEY(key, NULL,
1101                                    (pem_password_cb *)password_callback,
1102                                    &cb_data);
1103     }
1104 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
1105     else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
1106         pkey = load_netscape_key(err, key, file, key_descrip, format);
1107 #endif
1108 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
1109     else if (format == FORMAT_MSBLOB)
1110         pkey = b2i_PublicKey_bio(key);
1111 #endif
1112     else {
1113         BIO_printf(err, "bad input format specified for key file\n");
1114         goto end;
1115     }
1116  end:
1117     BIO_free(key);
1118     if (pkey == NULL)
1119         BIO_printf(err, "unable to load %s\n", key_descrip);
1120     return (pkey);
1121 }
1122
1123 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
1124 static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
1125                                    const char *key_descrip, int format)
1126 {
1127     EVP_PKEY *pkey;
1128     BUF_MEM *buf;
1129     RSA *rsa;
1130     const unsigned char *p;
1131     int size, i;
1132
1133     buf = BUF_MEM_new();
1134     pkey = EVP_PKEY_new();
1135     size = 0;
1136     if (buf == NULL || pkey == NULL)
1137         goto error;
1138     for (;;) {
1139         if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
1140             goto error;
1141         i = BIO_read(key, &(buf->data[size]), 1024 * 10);
1142         size += i;
1143         if (i == 0)
1144             break;
1145         if (i < 0) {
1146             BIO_printf(err, "Error reading %s %s", key_descrip, file);
1147             goto error;
1148         }
1149     }
1150     p = (unsigned char *)buf->data;
1151     rsa = d2i_RSA_NET(NULL, &p, (long)size, NULL,
1152                       (format == FORMAT_IISSGC ? 1 : 0));
1153     if (rsa == NULL)
1154         goto error;
1155     BUF_MEM_free(buf);
1156     EVP_PKEY_set1_RSA(pkey, rsa);
1157     return pkey;
1158  error:
1159     BUF_MEM_free(buf);
1160     EVP_PKEY_free(pkey);
1161     return NULL;
1162 }
1163 #endif                          /* ndef OPENSSL_NO_RC4 */
1164
1165 static int load_certs_crls(BIO *err, const char *file, int format,
1166                            const char *pass, ENGINE *e, const char *desc,
1167                            STACK_OF(X509) **pcerts,
1168                            STACK_OF(X509_CRL) **pcrls)
1169 {
1170     int i;
1171     BIO *bio;
1172     STACK_OF(X509_INFO) *xis = NULL;
1173     X509_INFO *xi;
1174     PW_CB_DATA cb_data;
1175     int rv = 0;
1176
1177     cb_data.password = pass;
1178     cb_data.prompt_info = file;
1179
1180     if (format != FORMAT_PEM) {
1181         BIO_printf(err, "bad input format specified for %s\n", desc);
1182         return 0;
1183     }
1184
1185     if (file == NULL)
1186         bio = BIO_new_fp(stdin, BIO_NOCLOSE);
1187     else
1188         bio = BIO_new_file(file, "r");
1189
1190     if (bio == NULL) {
1191         BIO_printf(err, "Error opening %s %s\n", desc, file ? file : "stdin");
1192         ERR_print_errors(err);
1193         return 0;
1194     }
1195
1196     xis = PEM_X509_INFO_read_bio(bio, NULL,
1197                                  (pem_password_cb *)password_callback,
1198                                  &cb_data);
1199
1200     BIO_free(bio);
1201
1202     if (pcerts) {
1203         *pcerts = sk_X509_new_null();
1204         if (!*pcerts)
1205             goto end;
1206     }
1207
1208     if (pcrls) {
1209         *pcrls = sk_X509_CRL_new_null();
1210         if (!*pcrls)
1211             goto end;
1212     }
1213
1214     for (i = 0; i < sk_X509_INFO_num(xis); i++) {
1215         xi = sk_X509_INFO_value(xis, i);
1216         if (xi->x509 && pcerts) {
1217             if (!sk_X509_push(*pcerts, xi->x509))
1218                 goto end;
1219             xi->x509 = NULL;
1220         }
1221         if (xi->crl && pcrls) {
1222             if (!sk_X509_CRL_push(*pcrls, xi->crl))
1223                 goto end;
1224             xi->crl = NULL;
1225         }
1226     }
1227
1228     if (pcerts && sk_X509_num(*pcerts) > 0)
1229         rv = 1;
1230
1231     if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
1232         rv = 1;
1233
1234  end:
1235
1236     if (xis)
1237         sk_X509_INFO_pop_free(xis, X509_INFO_free);
1238
1239     if (rv == 0) {
1240         if (pcerts) {
1241             sk_X509_pop_free(*pcerts, X509_free);
1242             *pcerts = NULL;
1243         }
1244         if (pcrls) {
1245             sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
1246             *pcrls = NULL;
1247         }
1248         BIO_printf(err, "unable to load %s\n",
1249                    pcerts ? "certificates" : "CRLs");
1250         ERR_print_errors(err);
1251     }
1252     return rv;
1253 }
1254
1255 STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
1256                            const char *pass, ENGINE *e, const char *desc)
1257 {
1258     STACK_OF(X509) *certs;
1259     if (!load_certs_crls(err, file, format, pass, e, desc, &certs, NULL))
1260         return NULL;
1261     return certs;
1262 }
1263
1264 STACK_OF(X509_CRL) *load_crls(BIO *err, const char *file, int format,
1265                               const char *pass, ENGINE *e, const char *desc)
1266 {
1267     STACK_OF(X509_CRL) *crls;
1268     if (!load_certs_crls(err, file, format, pass, e, desc, NULL, &crls))
1269         return NULL;
1270     return crls;
1271 }
1272
1273 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
1274 /* Return error for unknown extensions */
1275 #define X509V3_EXT_DEFAULT              0
1276 /* Print error for unknown extensions */
1277 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
1278 /* ASN1 parse unknown extensions */
1279 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
1280 /* BIO_dump unknown extensions */
1281 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
1282
1283 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1284                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1285
1286 int set_cert_ex(unsigned long *flags, const char *arg)
1287 {
1288     static const NAME_EX_TBL cert_tbl[] = {
1289         {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1290         {"ca_default", X509_FLAG_CA, 0xffffffffl},
1291         {"no_header", X509_FLAG_NO_HEADER, 0},
1292         {"no_version", X509_FLAG_NO_VERSION, 0},
1293         {"no_serial", X509_FLAG_NO_SERIAL, 0},
1294         {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1295         {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1296         {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1297         {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1298         {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1299         {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1300         {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1301         {"no_aux", X509_FLAG_NO_AUX, 0},
1302         {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1303         {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1304         {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1305         {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1306         {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1307         {NULL, 0, 0}
1308     };
1309     return set_multi_opts(flags, arg, cert_tbl);
1310 }
1311
1312 int set_name_ex(unsigned long *flags, const char *arg)
1313 {
1314     static const NAME_EX_TBL ex_tbl[] = {
1315         {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1316         {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1317         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1318         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1319         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1320         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1321         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1322         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1323         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1324         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1325         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1326         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1327         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1328         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1329         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1330         {"dn_rev", XN_FLAG_DN_REV, 0},
1331         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1332         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1333         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1334         {"align", XN_FLAG_FN_ALIGN, 0},
1335         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1336         {"space_eq", XN_FLAG_SPC_EQ, 0},
1337         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1338         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1339         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1340         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1341         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1342         {NULL, 0, 0}
1343     };
1344     return set_multi_opts(flags, arg, ex_tbl);
1345 }
1346
1347 int set_ext_copy(int *copy_type, const char *arg)
1348 {
1349     if (!strcasecmp(arg, "none"))
1350         *copy_type = EXT_COPY_NONE;
1351     else if (!strcasecmp(arg, "copy"))
1352         *copy_type = EXT_COPY_ADD;
1353     else if (!strcasecmp(arg, "copyall"))
1354         *copy_type = EXT_COPY_ALL;
1355     else
1356         return 0;
1357     return 1;
1358 }
1359
1360 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1361 {
1362     STACK_OF(X509_EXTENSION) *exts = NULL;
1363     X509_EXTENSION *ext, *tmpext;
1364     ASN1_OBJECT *obj;
1365     int i, idx, ret = 0;
1366     if (!x || !req || (copy_type == EXT_COPY_NONE))
1367         return 1;
1368     exts = X509_REQ_get_extensions(req);
1369
1370     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1371         ext = sk_X509_EXTENSION_value(exts, i);
1372         obj = X509_EXTENSION_get_object(ext);
1373         idx = X509_get_ext_by_OBJ(x, obj, -1);
1374         /* Does extension exist? */
1375         if (idx != -1) {
1376             /* If normal copy don't override existing extension */
1377             if (copy_type == EXT_COPY_ADD)
1378                 continue;
1379             /* Delete all extensions of same type */
1380             do {
1381                 tmpext = X509_get_ext(x, idx);
1382                 X509_delete_ext(x, idx);
1383                 X509_EXTENSION_free(tmpext);
1384                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1385             } while (idx != -1);
1386         }
1387         if (!X509_add_ext(x, ext, -1))
1388             goto end;
1389     }
1390
1391     ret = 1;
1392
1393  end:
1394
1395     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1396
1397     return ret;
1398 }
1399
1400 static int set_multi_opts(unsigned long *flags, const char *arg,
1401                           const NAME_EX_TBL * in_tbl)
1402 {
1403     STACK_OF(CONF_VALUE) *vals;
1404     CONF_VALUE *val;
1405     int i, ret = 1;
1406     if (!arg)
1407         return 0;
1408     vals = X509V3_parse_list(arg);
1409     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1410         val = sk_CONF_VALUE_value(vals, i);
1411         if (!set_table_opts(flags, val->name, in_tbl))
1412             ret = 0;
1413     }
1414     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1415     return ret;
1416 }
1417
1418 static int set_table_opts(unsigned long *flags, const char *arg,
1419                           const NAME_EX_TBL * in_tbl)
1420 {
1421     char c;
1422     const NAME_EX_TBL *ptbl;
1423     c = arg[0];
1424
1425     if (c == '-') {
1426         c = 0;
1427         arg++;
1428     } else if (c == '+') {
1429         c = 1;
1430         arg++;
1431     } else
1432         c = 1;
1433
1434     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1435         if (!strcasecmp(arg, ptbl->name)) {
1436             *flags &= ~ptbl->mask;
1437             if (c)
1438                 *flags |= ptbl->flag;
1439             else
1440                 *flags &= ~ptbl->flag;
1441             return 1;
1442         }
1443     }
1444     return 0;
1445 }
1446
1447 void print_name(BIO *out, const char *title, X509_NAME *nm,
1448                 unsigned long lflags)
1449 {
1450     char *buf;
1451     char mline = 0;
1452     int indent = 0;
1453
1454     if (title)
1455         BIO_puts(out, title);
1456     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1457         mline = 1;
1458         indent = 4;
1459     }
1460     if (lflags == XN_FLAG_COMPAT) {
1461         buf = X509_NAME_oneline(nm, 0, 0);
1462         BIO_puts(out, buf);
1463         BIO_puts(out, "\n");
1464         OPENSSL_free(buf);
1465     } else {
1466         if (mline)
1467             BIO_puts(out, "\n");
1468         X509_NAME_print_ex(out, nm, indent, lflags);
1469         BIO_puts(out, "\n");
1470     }
1471 }
1472
1473 X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
1474 {
1475     X509_STORE *store;
1476     X509_LOOKUP *lookup;
1477     if (!(store = X509_STORE_new()))
1478         goto end;
1479     lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1480     if (lookup == NULL)
1481         goto end;
1482     if (CAfile) {
1483         if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1484             BIO_printf(bp, "Error loading file %s\n", CAfile);
1485             goto end;
1486         }
1487     } else
1488         X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1489
1490     lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1491     if (lookup == NULL)
1492         goto end;
1493     if (CApath) {
1494         if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1495             BIO_printf(bp, "Error loading directory %s\n", CApath);
1496             goto end;
1497         }
1498     } else
1499         X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1500
1501     ERR_clear_error();
1502     return store;
1503  end:
1504     X509_STORE_free(store);
1505     return NULL;
1506 }
1507
1508 #ifndef OPENSSL_NO_ENGINE
1509 /* Try to load an engine in a shareable library */
1510 static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
1511 {
1512     ENGINE *e = ENGINE_by_id("dynamic");
1513     if (e) {
1514         if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1515             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1516             ENGINE_free(e);
1517             e = NULL;
1518         }
1519     }
1520     return e;
1521 }
1522
1523 ENGINE *setup_engine(BIO *err, const char *engine, int debug)
1524 {
1525     ENGINE *e = NULL;
1526
1527     if (engine) {
1528         if (strcmp(engine, "auto") == 0) {
1529             BIO_printf(err, "enabling auto ENGINE support\n");
1530             ENGINE_register_all_complete();
1531             return NULL;
1532         }
1533         if ((e = ENGINE_by_id(engine)) == NULL
1534             && (e = try_load_engine(err, engine, debug)) == NULL) {
1535             BIO_printf(err, "invalid engine \"%s\"\n", engine);
1536             ERR_print_errors(err);
1537             return NULL;
1538         }
1539         if (debug) {
1540             ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, err, 0);
1541         }
1542         ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1543         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1544             BIO_printf(err, "can't use that engine\n");
1545             ERR_print_errors(err);
1546             ENGINE_free(e);
1547             return NULL;
1548         }
1549
1550         BIO_printf(err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1551
1552         /* Free our "structural" reference. */
1553         ENGINE_free(e);
1554     }
1555     return e;
1556 }
1557 #endif
1558
1559 int load_config(BIO *err, CONF *cnf)
1560 {
1561     static int load_config_called = 0;
1562     if (load_config_called)
1563         return 1;
1564     load_config_called = 1;
1565     if (!cnf)
1566         cnf = config;
1567     if (!cnf)
1568         return 1;
1569
1570     OPENSSL_load_builtin_modules();
1571
1572     if (CONF_modules_load(cnf, NULL, 0) <= 0) {
1573         BIO_printf(err, "Error configuring OpenSSL\n");
1574         ERR_print_errors(err);
1575         return 0;
1576     }
1577     return 1;
1578 }
1579
1580 char *make_config_name()
1581 {
1582     const char *t = X509_get_default_cert_area();
1583     size_t len;
1584     char *p;
1585
1586     len = strlen(t) + strlen(OPENSSL_CONF) + 2;
1587     p = OPENSSL_malloc(len);
1588     if (p == NULL)
1589         return NULL;
1590     BUF_strlcpy(p, t, len);
1591 #ifndef OPENSSL_SYS_VMS
1592     BUF_strlcat(p, "/", len);
1593 #endif
1594     BUF_strlcat(p, OPENSSL_CONF, len);
1595
1596     return p;
1597 }
1598
1599 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1600 {
1601     const char *n;
1602
1603     n = a[DB_serial];
1604     while (*n == '0')
1605         n++;
1606     return (lh_strhash(n));
1607 }
1608
1609 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1610                             const OPENSSL_CSTRING *b)
1611 {
1612     const char *aa, *bb;
1613
1614     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1615     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1616     return (strcmp(aa, bb));
1617 }
1618
1619 static int index_name_qual(char **a)
1620 {
1621     return (a[0][0] == 'V');
1622 }
1623
1624 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1625 {
1626     return (lh_strhash(a[DB_name]));
1627 }
1628
1629 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1630 {
1631     return (strcmp(a[DB_name], b[DB_name]));
1632 }
1633
1634 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1635 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1636 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1637 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1638 #undef BSIZE
1639 #define BSIZE 256
1640 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1641 {
1642     BIO *in = NULL;
1643     BIGNUM *ret = NULL;
1644     char buf[1024];
1645     ASN1_INTEGER *ai = NULL;
1646
1647     ai = ASN1_INTEGER_new();
1648     if (ai == NULL)
1649         goto err;
1650
1651     if ((in = BIO_new(BIO_s_file())) == NULL) {
1652         ERR_print_errors(bio_err);
1653         goto err;
1654     }
1655
1656     if (BIO_read_filename(in, serialfile) <= 0) {
1657         if (!create) {
1658             perror(serialfile);
1659             goto err;
1660         } else {
1661             ret = BN_new();
1662             if (ret == NULL || !rand_serial(ret, ai))
1663                 BIO_printf(bio_err, "Out of memory\n");
1664         }
1665     } else {
1666         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1667             BIO_printf(bio_err, "unable to load number from %s\n",
1668                        serialfile);
1669             goto err;
1670         }
1671         ret = ASN1_INTEGER_to_BN(ai, NULL);
1672         if (ret == NULL) {
1673             BIO_printf(bio_err,
1674                        "error converting number from bin to BIGNUM\n");
1675             goto err;
1676         }
1677     }
1678
1679     if (ret && retai) {
1680         *retai = ai;
1681         ai = NULL;
1682     }
1683  err:
1684     BIO_free(in);
1685     if (ai != NULL)
1686         ASN1_INTEGER_free(ai);
1687     return (ret);
1688 }
1689
1690 int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
1691                 ASN1_INTEGER **retai)
1692 {
1693     char buf[1][BSIZE];
1694     BIO *out = NULL;
1695     int ret = 0;
1696     ASN1_INTEGER *ai = NULL;
1697     int j;
1698
1699     if (suffix == NULL)
1700         j = strlen(serialfile);
1701     else
1702         j = strlen(serialfile) + strlen(suffix) + 1;
1703     if (j >= BSIZE) {
1704         BIO_printf(bio_err, "file name too long\n");
1705         goto err;
1706     }
1707
1708     if (suffix == NULL)
1709         BUF_strlcpy(buf[0], serialfile, BSIZE);
1710     else {
1711 #ifndef OPENSSL_SYS_VMS
1712         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1713 #else
1714         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1715 #endif
1716     }
1717 #ifdef RL_DEBUG
1718     BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1719 #endif
1720     out = BIO_new(BIO_s_file());
1721     if (out == NULL) {
1722         ERR_print_errors(bio_err);
1723         goto err;
1724     }
1725     if (BIO_write_filename(out, buf[0]) <= 0) {
1726         perror(serialfile);
1727         goto err;
1728     }
1729
1730     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1731         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1732         goto err;
1733     }
1734     i2a_ASN1_INTEGER(out, ai);
1735     BIO_puts(out, "\n");
1736     ret = 1;
1737     if (retai) {
1738         *retai = ai;
1739         ai = NULL;
1740     }
1741  err:
1742     BIO_free_all(out);
1743     if (ai != NULL)
1744         ASN1_INTEGER_free(ai);
1745     return (ret);
1746 }
1747
1748 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1749 {
1750     char buf[5][BSIZE];
1751     int i, j;
1752
1753     i = strlen(serialfile) + strlen(old_suffix);
1754     j = strlen(serialfile) + strlen(new_suffix);
1755     if (i > j)
1756         j = i;
1757     if (j + 1 >= BSIZE) {
1758         BIO_printf(bio_err, "file name too long\n");
1759         goto err;
1760     }
1761 #ifndef OPENSSL_SYS_VMS
1762     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
1763 #else
1764     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
1765 #endif
1766 #ifndef OPENSSL_SYS_VMS
1767     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
1768 #else
1769     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
1770 #endif
1771 #ifdef RL_DEBUG
1772     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1773                serialfile, buf[1]);
1774 #endif
1775     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1776 #ifdef ENOTDIR
1777         && errno != ENOTDIR
1778 #endif
1779         ) {
1780         BIO_printf(bio_err,
1781                    "unable to rename %s to %s\n", serialfile, buf[1]);
1782         perror("reason");
1783         goto err;
1784     }
1785 #ifdef RL_DEBUG
1786     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1787                buf[0], serialfile);
1788 #endif
1789     if (rename(buf[0], serialfile) < 0) {
1790         BIO_printf(bio_err,
1791                    "unable to rename %s to %s\n", buf[0], serialfile);
1792         perror("reason");
1793         rename(buf[1], serialfile);
1794         goto err;
1795     }
1796     return 1;
1797  err:
1798     return 0;
1799 }
1800
1801 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1802 {
1803     BIGNUM *btmp;
1804     int ret = 0;
1805     if (b)
1806         btmp = b;
1807     else
1808         btmp = BN_new();
1809
1810     if (!btmp)
1811         return 0;
1812
1813     if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1814         goto error;
1815     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1816         goto error;
1817
1818     ret = 1;
1819
1820  error:
1821
1822     if (!b)
1823         BN_free(btmp);
1824
1825     return ret;
1826 }
1827
1828 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1829 {
1830     CA_DB *retdb = NULL;
1831     TXT_DB *tmpdb = NULL;
1832     BIO *in = BIO_new(BIO_s_file());
1833     CONF *dbattr_conf = NULL;
1834     char buf[1][BSIZE];
1835     long errorline = -1;
1836
1837     if (in == NULL) {
1838         ERR_print_errors(bio_err);
1839         goto err;
1840     }
1841     if (BIO_read_filename(in, dbfile) <= 0) {
1842         perror(dbfile);
1843         BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1844         goto err;
1845     }
1846     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1847         goto err;
1848
1849 #ifndef OPENSSL_SYS_VMS
1850     BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1851 #else
1852     BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1853 #endif
1854     dbattr_conf = NCONF_new(NULL);
1855     if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
1856         if (errorline > 0) {
1857             BIO_printf(bio_err,
1858                        "error on line %ld of db attribute file '%s'\n",
1859                        errorline, buf[0]);
1860             goto err;
1861         } else {
1862             NCONF_free(dbattr_conf);
1863             dbattr_conf = NULL;
1864         }
1865     }
1866
1867     if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL) {
1868         fprintf(stderr, "Out of memory\n");
1869         goto err;
1870     }
1871
1872     retdb->db = tmpdb;
1873     tmpdb = NULL;
1874     if (db_attr)
1875         retdb->attributes = *db_attr;
1876     else {
1877         retdb->attributes.unique_subject = 1;
1878     }
1879
1880     if (dbattr_conf) {
1881         char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1882         if (p) {
1883 #ifdef RL_DEBUG
1884             BIO_printf(bio_err,
1885                        "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1886 #endif
1887             retdb->attributes.unique_subject = parse_yesno(p, 1);
1888         }
1889     }
1890
1891  err:
1892     if (dbattr_conf)
1893         NCONF_free(dbattr_conf);
1894     if (tmpdb)
1895         TXT_DB_free(tmpdb);
1896     BIO_free_all(in);
1897     return retdb;
1898 }
1899
1900 int index_index(CA_DB *db)
1901 {
1902     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1903                              LHASH_HASH_FN(index_serial),
1904                              LHASH_COMP_FN(index_serial))) {
1905         BIO_printf(bio_err,
1906                    "error creating serial number index:(%ld,%ld,%ld)\n",
1907                    db->db->error, db->db->arg1, db->db->arg2);
1908         return 0;
1909     }
1910
1911     if (db->attributes.unique_subject
1912         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1913                                 LHASH_HASH_FN(index_name),
1914                                 LHASH_COMP_FN(index_name))) {
1915         BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1916                    db->db->error, db->db->arg1, db->db->arg2);
1917         return 0;
1918     }
1919     return 1;
1920 }
1921
1922 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1923 {
1924     char buf[3][BSIZE];
1925     BIO *out = BIO_new(BIO_s_file());
1926     int j;
1927
1928     if (out == NULL) {
1929         ERR_print_errors(bio_err);
1930         goto err;
1931     }
1932
1933     j = strlen(dbfile) + strlen(suffix);
1934     if (j + 6 >= BSIZE) {
1935         BIO_printf(bio_err, "file name too long\n");
1936         goto err;
1937     }
1938 #ifndef OPENSSL_SYS_VMS
1939     j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1940 #else
1941     j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1942 #endif
1943 #ifndef OPENSSL_SYS_VMS
1944     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1945 #else
1946     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1947 #endif
1948 #ifndef OPENSSL_SYS_VMS
1949     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1950 #else
1951     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1952 #endif
1953 #ifdef RL_DEBUG
1954     BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1955 #endif
1956     if (BIO_write_filename(out, buf[0]) <= 0) {
1957         perror(dbfile);
1958         BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1959         goto err;
1960     }
1961     j = TXT_DB_write(out, db->db);
1962     if (j <= 0)
1963         goto err;
1964
1965     BIO_free(out);
1966
1967     out = BIO_new(BIO_s_file());
1968 #ifdef RL_DEBUG
1969     BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1970 #endif
1971     if (BIO_write_filename(out, buf[1]) <= 0) {
1972         perror(buf[2]);
1973         BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1974         goto err;
1975     }
1976     BIO_printf(out, "unique_subject = %s\n",
1977                db->attributes.unique_subject ? "yes" : "no");
1978     BIO_free(out);
1979
1980     return 1;
1981  err:
1982     return 0;
1983 }
1984
1985 int rotate_index(const char *dbfile, const char *new_suffix,
1986                  const char *old_suffix)
1987 {
1988     char buf[5][BSIZE];
1989     int i, j;
1990
1991     i = strlen(dbfile) + strlen(old_suffix);
1992     j = strlen(dbfile) + strlen(new_suffix);
1993     if (i > j)
1994         j = i;
1995     if (j + 6 >= BSIZE) {
1996         BIO_printf(bio_err, "file name too long\n");
1997         goto err;
1998     }
1999 #ifndef OPENSSL_SYS_VMS
2000     j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
2001 #else
2002     j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
2003 #endif
2004 #ifndef OPENSSL_SYS_VMS
2005     j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
2006 #else
2007     j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s", dbfile, new_suffix);
2008 #endif
2009 #ifndef OPENSSL_SYS_VMS
2010     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
2011 #else
2012     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, new_suffix);
2013 #endif
2014 #ifndef OPENSSL_SYS_VMS
2015     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
2016 #else
2017     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", dbfile, old_suffix);
2018 #endif
2019 #ifndef OPENSSL_SYS_VMS
2020     j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
2021 #else
2022     j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s", dbfile, old_suffix);
2023 #endif
2024 #ifdef RL_DEBUG
2025     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", dbfile, buf[1]);
2026 #endif
2027     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
2028 #ifdef ENOTDIR
2029         && errno != ENOTDIR
2030 #endif
2031         ) {
2032         BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
2033         perror("reason");
2034         goto err;
2035     }
2036 #ifdef RL_DEBUG
2037     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[0], dbfile);
2038 #endif
2039     if (rename(buf[0], dbfile) < 0) {
2040         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
2041         perror("reason");
2042         rename(buf[1], dbfile);
2043         goto err;
2044     }
2045 #ifdef RL_DEBUG
2046     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[4], buf[3]);
2047 #endif
2048     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
2049 #ifdef ENOTDIR
2050         && errno != ENOTDIR
2051 #endif
2052         ) {
2053         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
2054         perror("reason");
2055         rename(dbfile, buf[0]);
2056         rename(buf[1], dbfile);
2057         goto err;
2058     }
2059 #ifdef RL_DEBUG
2060     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[2], buf[4]);
2061 #endif
2062     if (rename(buf[2], buf[4]) < 0) {
2063         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
2064         perror("reason");
2065         rename(buf[3], buf[4]);
2066         rename(dbfile, buf[0]);
2067         rename(buf[1], dbfile);
2068         goto err;
2069     }
2070     return 1;
2071  err:
2072     return 0;
2073 }
2074
2075 void free_index(CA_DB *db)
2076 {
2077     if (db) {
2078         if (db->db)
2079             TXT_DB_free(db->db);
2080         OPENSSL_free(db);
2081     }
2082 }
2083
2084 int parse_yesno(const char *str, int def)
2085 {
2086     int ret = def;
2087     if (str) {
2088         switch (*str) {
2089         case 'f':              /* false */
2090         case 'F':              /* FALSE */
2091         case 'n':              /* no */
2092         case 'N':              /* NO */
2093         case '0':              /* 0 */
2094             ret = 0;
2095             break;
2096         case 't':              /* true */
2097         case 'T':              /* TRUE */
2098         case 'y':              /* yes */
2099         case 'Y':              /* YES */
2100         case '1':              /* 1 */
2101             ret = 1;
2102             break;
2103         default:
2104             ret = def;
2105             break;
2106         }
2107     }
2108     return ret;
2109 }
2110
2111 /*
2112  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
2113  * where characters may be escaped by \
2114  */
2115 X509_NAME *parse_name(char *subject, long chtype, int multirdn)
2116 {
2117     size_t buflen = strlen(subject) + 1; /* to copy the types and values
2118                                           * into. due to escaping, the copy
2119                                           * can only become shorter */
2120     char *buf = OPENSSL_malloc(buflen);
2121     size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
2122     char **ne_types = OPENSSL_malloc(max_ne * sizeof(char *));
2123     char **ne_values = OPENSSL_malloc(max_ne * sizeof(char *));
2124     int *mval = OPENSSL_malloc(max_ne * sizeof(int));
2125
2126     char *sp = subject, *bp = buf;
2127     int i, ne_num = 0;
2128
2129     X509_NAME *n = NULL;
2130     int nid;
2131
2132     if (!buf || !ne_types || !ne_values || !mval) {
2133         BIO_printf(bio_err, "malloc error\n");
2134         goto error;
2135     }
2136
2137     if (*subject != '/') {
2138         BIO_printf(bio_err, "Subject does not start with '/'.\n");
2139         goto error;
2140     }
2141     sp++;                       /* skip leading / */
2142
2143     /* no multivalued RDN by default */
2144     mval[ne_num] = 0;
2145
2146     while (*sp) {
2147         /* collect type */
2148         ne_types[ne_num] = bp;
2149         while (*sp) {
2150             if (*sp == '\\') {  /* is there anything to escape in the
2151                                  * type...? */
2152                 if (*++sp)
2153                     *bp++ = *sp++;
2154                 else {
2155                     BIO_printf(bio_err,
2156                                "escape character at end of string\n");
2157                     goto error;
2158                 }
2159             } else if (*sp == '=') {
2160                 sp++;
2161                 *bp++ = '\0';
2162                 break;
2163             } else
2164                 *bp++ = *sp++;
2165         }
2166         if (!*sp) {
2167             BIO_printf(bio_err,
2168                        "end of string encountered while processing type of subject name element #%d\n",
2169                        ne_num);
2170             goto error;
2171         }
2172         ne_values[ne_num] = bp;
2173         while (*sp) {
2174             if (*sp == '\\') {
2175                 if (*++sp)
2176                     *bp++ = *sp++;
2177                 else {
2178                     BIO_printf(bio_err,
2179                                "escape character at end of string\n");
2180                     goto error;
2181                 }
2182             } else if (*sp == '/') {
2183                 sp++;
2184                 /* no multivalued RDN by default */
2185                 mval[ne_num + 1] = 0;
2186                 break;
2187             } else if (*sp == '+' && multirdn) {
2188                 /*
2189                  * a not escaped + signals a mutlivalued RDN
2190                  */
2191                 sp++;
2192                 mval[ne_num + 1] = -1;
2193                 break;
2194             } else
2195                 *bp++ = *sp++;
2196         }
2197         *bp++ = '\0';
2198         ne_num++;
2199     }
2200
2201     if (!(n = X509_NAME_new()))
2202         goto error;
2203
2204     for (i = 0; i < ne_num; i++) {
2205         if ((nid = OBJ_txt2nid(ne_types[i])) == NID_undef) {
2206             BIO_printf(bio_err,
2207                        "Subject Attribute %s has no known NID, skipped\n",
2208                        ne_types[i]);
2209             continue;
2210         }
2211
2212         if (!*ne_values[i]) {
2213             BIO_printf(bio_err,
2214                        "No value provided for Subject Attribute %s, skipped\n",
2215                        ne_types[i]);
2216             continue;
2217         }
2218
2219         if (!X509_NAME_add_entry_by_NID
2220             (n, nid, chtype, (unsigned char *)ne_values[i], -1, -1, mval[i]))
2221             goto error;
2222     }
2223
2224     OPENSSL_free(ne_values);
2225     OPENSSL_free(ne_types);
2226     OPENSSL_free(buf);
2227     OPENSSL_free(mval);
2228     return n;
2229
2230  error:
2231     X509_NAME_free(n);
2232     if (ne_values)
2233         OPENSSL_free(ne_values);
2234     if (ne_types)
2235         OPENSSL_free(ne_types);
2236     if (mval)
2237         OPENSSL_free(mval);
2238     if (buf)
2239         OPENSSL_free(buf);
2240     return NULL;
2241 }
2242
2243 int args_verify(char ***pargs, int *pargc,
2244                 int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
2245 {
2246     ASN1_OBJECT *otmp = NULL;
2247     unsigned long flags = 0;
2248     int i;
2249     int purpose = 0, depth = -1;
2250     char **oldargs = *pargs;
2251     char *arg = **pargs, *argn = (*pargs)[1];
2252     const X509_VERIFY_PARAM *vpm = NULL;
2253     time_t at_time = 0;
2254     char *hostname = NULL;
2255     char *email = NULL;
2256     char *ipasc = NULL;
2257     if (!strcmp(arg, "-policy")) {
2258         if (!argn)
2259             *badarg = 1;
2260         else {
2261             otmp = OBJ_txt2obj(argn, 0);
2262             if (!otmp) {
2263                 BIO_printf(err, "Invalid Policy \"%s\"\n", argn);
2264                 *badarg = 1;
2265             }
2266         }
2267         (*pargs)++;
2268     } else if (strcmp(arg, "-purpose") == 0) {
2269         X509_PURPOSE *xptmp;
2270         if (!argn)
2271             *badarg = 1;
2272         else {
2273             i = X509_PURPOSE_get_by_sname(argn);
2274             if (i < 0) {
2275                 BIO_printf(err, "unrecognized purpose\n");
2276                 *badarg = 1;
2277             } else {
2278                 xptmp = X509_PURPOSE_get0(i);
2279                 purpose = X509_PURPOSE_get_id(xptmp);
2280             }
2281         }
2282         (*pargs)++;
2283     } else if (strcmp(arg, "-verify_name") == 0) {
2284         if (!argn)
2285             *badarg = 1;
2286         else {
2287             vpm = X509_VERIFY_PARAM_lookup(argn);
2288             if (!vpm) {
2289                 BIO_printf(err, "unrecognized verify name\n");
2290                 *badarg = 1;
2291             }
2292         }
2293         (*pargs)++;
2294     } else if (strcmp(arg, "-verify_depth") == 0) {
2295         if (!argn)
2296             *badarg = 1;
2297         else {
2298             depth = atoi(argn);
2299             if (depth < 0) {
2300                 BIO_printf(err, "invalid depth\n");
2301                 *badarg = 1;
2302             }
2303         }
2304         (*pargs)++;
2305     } else if (strcmp(arg, "-attime") == 0) {
2306         if (!argn)
2307             *badarg = 1;
2308         else {
2309             long timestamp;
2310             /*
2311              * interpret the -attime argument as seconds since Epoch
2312              */
2313             if (sscanf(argn, "%li", &timestamp) != 1) {
2314                 BIO_printf(bio_err, "Error parsing timestamp %s\n", argn);
2315                 *badarg = 1;
2316             }
2317             /* on some platforms time_t may be a float */
2318             at_time = (time_t)timestamp;
2319         }
2320         (*pargs)++;
2321     } else if (strcmp(arg, "-verify_hostname") == 0) {
2322         if (!argn)
2323             *badarg = 1;
2324         hostname = argn;
2325         (*pargs)++;
2326     } else if (strcmp(arg, "-verify_email") == 0) {
2327         if (!argn)
2328             *badarg = 1;
2329         email = argn;
2330         (*pargs)++;
2331     } else if (strcmp(arg, "-verify_ip") == 0) {
2332         if (!argn)
2333             *badarg = 1;
2334         ipasc = argn;
2335         (*pargs)++;
2336     } else if (!strcmp(arg, "-ignore_critical"))
2337         flags |= X509_V_FLAG_IGNORE_CRITICAL;
2338     else if (!strcmp(arg, "-issuer_checks"))
2339         flags |= X509_V_FLAG_CB_ISSUER_CHECK;
2340     else if (!strcmp(arg, "-crl_check"))
2341         flags |= X509_V_FLAG_CRL_CHECK;
2342     else if (!strcmp(arg, "-crl_check_all"))
2343         flags |= X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
2344     else if (!strcmp(arg, "-policy_check"))
2345         flags |= X509_V_FLAG_POLICY_CHECK;
2346     else if (!strcmp(arg, "-explicit_policy"))
2347         flags |= X509_V_FLAG_EXPLICIT_POLICY;
2348     else if (!strcmp(arg, "-inhibit_any"))
2349         flags |= X509_V_FLAG_INHIBIT_ANY;
2350     else if (!strcmp(arg, "-inhibit_map"))
2351         flags |= X509_V_FLAG_INHIBIT_MAP;
2352     else if (!strcmp(arg, "-x509_strict"))
2353         flags |= X509_V_FLAG_X509_STRICT;
2354     else if (!strcmp(arg, "-extended_crl"))
2355         flags |= X509_V_FLAG_EXTENDED_CRL_SUPPORT;
2356     else if (!strcmp(arg, "-use_deltas"))
2357         flags |= X509_V_FLAG_USE_DELTAS;
2358     else if (!strcmp(arg, "-policy_print"))
2359         flags |= X509_V_FLAG_NOTIFY_POLICY;
2360     else if (!strcmp(arg, "-check_ss_sig"))
2361         flags |= X509_V_FLAG_CHECK_SS_SIGNATURE;
2362     else if (!strcmp(arg, "-trusted_first"))
2363         flags |= X509_V_FLAG_TRUSTED_FIRST;
2364     else if (!strcmp(arg, "-suiteB_128_only"))
2365         flags |= X509_V_FLAG_SUITEB_128_LOS_ONLY;
2366     else if (!strcmp(arg, "-suiteB_128"))
2367         flags |= X509_V_FLAG_SUITEB_128_LOS;
2368     else if (!strcmp(arg, "-suiteB_192"))
2369         flags |= X509_V_FLAG_SUITEB_192_LOS;
2370     else if (!strcmp(arg, "-partial_chain"))
2371         flags |= X509_V_FLAG_PARTIAL_CHAIN;
2372     else if (!strcmp(arg, "-no_alt_chains"))
2373         flags |= X509_V_FLAG_NO_ALT_CHAINS;
2374     else
2375         return 0;
2376
2377     if (*badarg) {
2378         if (*pm)
2379             X509_VERIFY_PARAM_free(*pm);
2380         *pm = NULL;
2381         goto end;
2382     }
2383
2384     if (!*pm && !(*pm = X509_VERIFY_PARAM_new())) {
2385         *badarg = 1;
2386         goto end;
2387     }
2388
2389     if (vpm)
2390         X509_VERIFY_PARAM_set1(*pm, vpm);
2391
2392     if (otmp)
2393         X509_VERIFY_PARAM_add0_policy(*pm, otmp);
2394     if (flags)
2395         X509_VERIFY_PARAM_set_flags(*pm, flags);
2396
2397     if (purpose)
2398         X509_VERIFY_PARAM_set_purpose(*pm, purpose);
2399
2400     if (depth >= 0)
2401         X509_VERIFY_PARAM_set_depth(*pm, depth);
2402
2403     if (at_time)
2404         X509_VERIFY_PARAM_set_time(*pm, at_time);
2405
2406     if (hostname && !X509_VERIFY_PARAM_set1_host(*pm, hostname, 0))
2407         *badarg = 1;
2408
2409     if (email && !X509_VERIFY_PARAM_set1_email(*pm, email, 0))
2410         *badarg = 1;
2411
2412     if (ipasc && !X509_VERIFY_PARAM_set1_ip_asc(*pm, ipasc))
2413         *badarg = 1;
2414
2415  end:
2416
2417     (*pargs)++;
2418
2419     if (pargc)
2420         *pargc -= *pargs - oldargs;
2421
2422     return 1;
2423
2424 }
2425
2426 /*
2427  * Read whole contents of a BIO into an allocated memory buffer and return
2428  * it.
2429  */
2430
2431 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
2432 {
2433     BIO *mem;
2434     int len, ret;
2435     unsigned char tbuf[1024];
2436     mem = BIO_new(BIO_s_mem());
2437     if (!mem)
2438         return -1;
2439     for (;;) {
2440         if ((maxlen != -1) && maxlen < 1024)
2441             len = maxlen;
2442         else
2443             len = 1024;
2444         len = BIO_read(in, tbuf, len);
2445         if (len <= 0)
2446             break;
2447         if (BIO_write(mem, tbuf, len) != len) {
2448             BIO_free(mem);
2449             return -1;
2450         }
2451         maxlen -= len;
2452
2453         if (maxlen == 0)
2454             break;
2455     }
2456     ret = BIO_get_mem_data(mem, (char **)out);
2457     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
2458     BIO_free(mem);
2459     return ret;
2460 }
2461
2462 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value)
2463 {
2464     int rv;
2465     char *stmp, *vtmp = NULL;
2466     stmp = BUF_strdup(value);
2467     if (!stmp)
2468         return -1;
2469     vtmp = strchr(stmp, ':');
2470     if (vtmp) {
2471         *vtmp = 0;
2472         vtmp++;
2473     }
2474     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2475     OPENSSL_free(stmp);
2476     return rv;
2477 }
2478
2479 static void nodes_print(BIO *out, const char *name,
2480                         STACK_OF(X509_POLICY_NODE) *nodes)
2481 {
2482     X509_POLICY_NODE *node;
2483     int i;
2484     BIO_printf(out, "%s Policies:", name);
2485     if (nodes) {
2486         BIO_puts(out, "\n");
2487         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2488             node = sk_X509_POLICY_NODE_value(nodes, i);
2489             X509_POLICY_NODE_print(out, node, 2);
2490         }
2491     } else
2492         BIO_puts(out, " <empty>\n");
2493 }
2494
2495 void policies_print(BIO *out, X509_STORE_CTX *ctx)
2496 {
2497     X509_POLICY_TREE *tree;
2498     int explicit_policy;
2499     int free_out = 0;
2500     if (out == NULL) {
2501         out = BIO_new_fp(stderr, BIO_NOCLOSE);
2502         free_out = 1;
2503     }
2504     tree = X509_STORE_CTX_get0_policy_tree(ctx);
2505     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2506
2507     BIO_printf(out, "Require explicit Policy: %s\n",
2508                explicit_policy ? "True" : "False");
2509
2510     nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
2511     nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
2512     if (free_out)
2513         BIO_free(out);
2514 }
2515
2516 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
2517
2518 static JPAKE_CTX *jpake_init(const char *us, const char *them,
2519                              const char *secret)
2520 {
2521     BIGNUM *p = NULL;
2522     BIGNUM *g = NULL;
2523     BIGNUM *q = NULL;
2524     BIGNUM *bnsecret = BN_new();
2525     JPAKE_CTX *ctx;
2526
2527     /* Use a safe prime for p (that we found earlier) */
2528     BN_hex2bn(&p,
2529               "F9E5B365665EA7A05A9C534502780FEE6F1AB5BD4F49947FD036DBD7E905269AF46EF28B0FC07487EE4F5D20FB3C0AF8E700F3A2FA3414970CBED44FEDFF80CE78D800F184BB82435D137AADA2C6C16523247930A63B85661D1FC817A51ACD96168E95898A1F83A79FFB529368AA7833ABD1B0C3AEDDB14D2E1A2F71D99F763F");
2530     g = BN_new();
2531     BN_set_word(g, 2);
2532     q = BN_new();
2533     BN_rshift1(q, p);
2534
2535     BN_bin2bn((const unsigned char *)secret, strlen(secret), bnsecret);
2536
2537     ctx = JPAKE_CTX_new(us, them, p, g, q, bnsecret);
2538     BN_free(bnsecret);
2539     BN_free(q);
2540     BN_free(g);
2541     BN_free(p);
2542
2543     return ctx;
2544 }
2545
2546 static void jpake_send_part(BIO *conn, const JPAKE_STEP_PART *p)
2547 {
2548     BN_print(conn, p->gx);
2549     BIO_puts(conn, "\n");
2550     BN_print(conn, p->zkpx.gr);
2551     BIO_puts(conn, "\n");
2552     BN_print(conn, p->zkpx.b);
2553     BIO_puts(conn, "\n");
2554 }
2555
2556 static void jpake_send_step1(BIO *bconn, JPAKE_CTX *ctx)
2557 {
2558     JPAKE_STEP1 s1;
2559
2560     JPAKE_STEP1_init(&s1);
2561     JPAKE_STEP1_generate(&s1, ctx);
2562     jpake_send_part(bconn, &s1.p1);
2563     jpake_send_part(bconn, &s1.p2);
2564     (void)BIO_flush(bconn);
2565     JPAKE_STEP1_release(&s1);
2566 }
2567
2568 static void jpake_send_step2(BIO *bconn, JPAKE_CTX *ctx)
2569 {
2570     JPAKE_STEP2 s2;
2571
2572     JPAKE_STEP2_init(&s2);
2573     JPAKE_STEP2_generate(&s2, ctx);
2574     jpake_send_part(bconn, &s2);
2575     (void)BIO_flush(bconn);
2576     JPAKE_STEP2_release(&s2);
2577 }
2578
2579 static void jpake_send_step3a(BIO *bconn, JPAKE_CTX *ctx)
2580 {
2581     JPAKE_STEP3A s3a;
2582
2583     JPAKE_STEP3A_init(&s3a);
2584     JPAKE_STEP3A_generate(&s3a, ctx);
2585     BIO_write(bconn, s3a.hhk, sizeof s3a.hhk);
2586     (void)BIO_flush(bconn);
2587     JPAKE_STEP3A_release(&s3a);
2588 }
2589
2590 static void jpake_send_step3b(BIO *bconn, JPAKE_CTX *ctx)
2591 {
2592     JPAKE_STEP3B s3b;
2593
2594     JPAKE_STEP3B_init(&s3b);
2595     JPAKE_STEP3B_generate(&s3b, ctx);
2596     BIO_write(bconn, s3b.hk, sizeof s3b.hk);
2597     (void)BIO_flush(bconn);
2598     JPAKE_STEP3B_release(&s3b);
2599 }
2600
2601 static void readbn(BIGNUM **bn, BIO *bconn)
2602 {
2603     char buf[10240];
2604     int l;
2605
2606     l = BIO_gets(bconn, buf, sizeof buf);
2607     assert(l > 0);
2608     assert(buf[l - 1] == '\n');
2609     buf[l - 1] = '\0';
2610     BN_hex2bn(bn, buf);
2611 }
2612
2613 static void jpake_receive_part(JPAKE_STEP_PART *p, BIO *bconn)
2614 {
2615     readbn(&p->gx, bconn);
2616     readbn(&p->zkpx.gr, bconn);
2617     readbn(&p->zkpx.b, bconn);
2618 }
2619
2620 static void jpake_receive_step1(JPAKE_CTX *ctx, BIO *bconn)
2621 {
2622     JPAKE_STEP1 s1;
2623
2624     JPAKE_STEP1_init(&s1);
2625     jpake_receive_part(&s1.p1, bconn);
2626     jpake_receive_part(&s1.p2, bconn);
2627     if (!JPAKE_STEP1_process(ctx, &s1)) {
2628         ERR_print_errors(bio_err);
2629         exit(1);
2630     }
2631     JPAKE_STEP1_release(&s1);
2632 }
2633
2634 static void jpake_receive_step2(JPAKE_CTX *ctx, BIO *bconn)
2635 {
2636     JPAKE_STEP2 s2;
2637
2638     JPAKE_STEP2_init(&s2);
2639     jpake_receive_part(&s2, bconn);
2640     if (!JPAKE_STEP2_process(ctx, &s2)) {
2641         ERR_print_errors(bio_err);
2642         exit(1);
2643     }
2644     JPAKE_STEP2_release(&s2);
2645 }
2646
2647 static void jpake_receive_step3a(JPAKE_CTX *ctx, BIO *bconn)
2648 {
2649     JPAKE_STEP3A s3a;
2650     int l;
2651
2652     JPAKE_STEP3A_init(&s3a);
2653     l = BIO_read(bconn, s3a.hhk, sizeof s3a.hhk);
2654     assert(l == sizeof s3a.hhk);
2655     if (!JPAKE_STEP3A_process(ctx, &s3a)) {
2656         ERR_print_errors(bio_err);
2657         exit(1);
2658     }
2659     JPAKE_STEP3A_release(&s3a);
2660 }
2661
2662 static void jpake_receive_step3b(JPAKE_CTX *ctx, BIO *bconn)
2663 {
2664     JPAKE_STEP3B s3b;
2665     int l;
2666
2667     JPAKE_STEP3B_init(&s3b);
2668     l = BIO_read(bconn, s3b.hk, sizeof s3b.hk);
2669     assert(l == sizeof s3b.hk);
2670     if (!JPAKE_STEP3B_process(ctx, &s3b)) {
2671         ERR_print_errors(bio_err);
2672         exit(1);
2673     }
2674     JPAKE_STEP3B_release(&s3b);
2675 }
2676
2677 void jpake_client_auth(BIO *out, BIO *conn, const char *secret)
2678 {
2679     JPAKE_CTX *ctx;
2680     BIO *bconn;
2681
2682     BIO_puts(out, "Authenticating with JPAKE\n");
2683
2684     ctx = jpake_init("client", "server", secret);
2685
2686     bconn = BIO_new(BIO_f_buffer());
2687     BIO_push(bconn, conn);
2688
2689     jpake_send_step1(bconn, ctx);
2690     jpake_receive_step1(ctx, bconn);
2691     jpake_send_step2(bconn, ctx);
2692     jpake_receive_step2(ctx, bconn);
2693     jpake_send_step3a(bconn, ctx);
2694     jpake_receive_step3b(ctx, bconn);
2695
2696     BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
2697
2698     if (psk_key)
2699         OPENSSL_free(psk_key);
2700
2701     psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
2702
2703     BIO_pop(bconn);
2704     BIO_free(bconn);
2705
2706     JPAKE_CTX_free(ctx);
2707 }
2708
2709 void jpake_server_auth(BIO *out, BIO *conn, const char *secret)
2710 {
2711     JPAKE_CTX *ctx;
2712     BIO *bconn;
2713
2714     BIO_puts(out, "Authenticating with JPAKE\n");
2715
2716     ctx = jpake_init("server", "client", secret);
2717
2718     bconn = BIO_new(BIO_f_buffer());
2719     BIO_push(bconn, conn);
2720
2721     jpake_receive_step1(ctx, bconn);
2722     jpake_send_step1(bconn, ctx);
2723     jpake_receive_step2(ctx, bconn);
2724     jpake_send_step2(bconn, ctx);
2725     jpake_receive_step3a(ctx, bconn);
2726     jpake_send_step3b(bconn, ctx);
2727
2728     BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
2729
2730     if (psk_key)
2731         OPENSSL_free(psk_key);
2732
2733     psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
2734
2735     BIO_pop(bconn);
2736     BIO_free(bconn);
2737
2738     JPAKE_CTX_free(ctx);
2739 }
2740
2741 #endif
2742
2743 #ifndef OPENSSL_NO_TLSEXT
2744 /*-
2745  * next_protos_parse parses a comma separated list of strings into a string
2746  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2747  *   outlen: (output) set to the length of the resulting buffer on success.
2748  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
2749  *   in: a NUL termianted string like "abc,def,ghi"
2750  *
2751  *   returns: a malloced buffer or NULL on failure.
2752  */
2753 unsigned char *next_protos_parse(unsigned short *outlen, const char *in)
2754 {
2755     size_t len;
2756     unsigned char *out;
2757     size_t i, start = 0;
2758
2759     len = strlen(in);
2760     if (len >= 65535)
2761         return NULL;
2762
2763     out = OPENSSL_malloc(strlen(in) + 1);
2764     if (!out)
2765         return NULL;
2766
2767     for (i = 0; i <= len; ++i) {
2768         if (i == len || in[i] == ',') {
2769             if (i - start > 255) {
2770                 OPENSSL_free(out);
2771                 return NULL;
2772             }
2773             out[start] = i - start;
2774             start = i + 1;
2775         } else
2776             out[i + 1] = in[i];
2777     }
2778
2779     *outlen = len + 1;
2780     return out;
2781 }
2782 #endif                          /* ndef OPENSSL_NO_TLSEXT */
2783
2784 void print_cert_checks(BIO *bio, X509 *x,
2785                        const char *checkhost,
2786                        const char *checkemail, const char *checkip)
2787 {
2788     if (x == NULL)
2789         return;
2790     if (checkhost) {
2791         BIO_printf(bio, "Hostname %s does%s match certificate\n",
2792                    checkhost, X509_check_host(x, checkhost, 0, 0, NULL) == 1
2793                    ? "" : " NOT");
2794     }
2795
2796     if (checkemail) {
2797         BIO_printf(bio, "Email %s does%s match certificate\n",
2798                    checkemail, X509_check_email(x, checkemail, 0,
2799                                                 0) ? "" : " NOT");
2800     }
2801
2802     if (checkip) {
2803         BIO_printf(bio, "IP %s does%s match certificate\n",
2804                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2805     }
2806 }
2807
2808 /* Get first http URL from a DIST_POINT structure */
2809
2810 static const char *get_dp_url(DIST_POINT *dp)
2811 {
2812     GENERAL_NAMES *gens;
2813     GENERAL_NAME *gen;
2814     int i, gtype;
2815     ASN1_STRING *uri;
2816     if (!dp->distpoint || dp->distpoint->type != 0)
2817         return NULL;
2818     gens = dp->distpoint->name.fullname;
2819     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2820         gen = sk_GENERAL_NAME_value(gens, i);
2821         uri = GENERAL_NAME_get0_value(gen, &gtype);
2822         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2823             char *uptr = (char *)ASN1_STRING_data(uri);
2824             if (!strncmp(uptr, "http://", 7))
2825                 return uptr;
2826         }
2827     }
2828     return NULL;
2829 }
2830
2831 /*
2832  * Look through a CRLDP structure and attempt to find an http URL to
2833  * downloads a CRL from.
2834  */
2835
2836 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2837 {
2838     int i;
2839     const char *urlptr = NULL;
2840     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2841         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2842         urlptr = get_dp_url(dp);
2843         if (urlptr)
2844             return load_crl(urlptr, FORMAT_HTTP);
2845     }
2846     return NULL;
2847 }
2848
2849 /*
2850  * Example of downloading CRLs from CRLDP: not usable for real world as it
2851  * always downloads, doesn't support non-blocking I/O and doesn't cache
2852  * anything.
2853  */
2854
2855 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
2856 {
2857     X509 *x;
2858     STACK_OF(X509_CRL) *crls = NULL;
2859     X509_CRL *crl;
2860     STACK_OF(DIST_POINT) *crldp;
2861     x = X509_STORE_CTX_get_current_cert(ctx);
2862     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2863     crl = load_crl_crldp(crldp);
2864     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2865     if (!crl)
2866         return NULL;
2867     crls = sk_X509_CRL_new_null();
2868     sk_X509_CRL_push(crls, crl);
2869     /* Try to download delta CRL */
2870     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2871     crl = load_crl_crldp(crldp);
2872     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2873     if (crl)
2874         sk_X509_CRL_push(crls, crl);
2875     return crls;
2876 }
2877
2878 void store_setup_crl_download(X509_STORE *st)
2879 {
2880     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2881 }
2882
2883 /*
2884  * Platform-specific sections
2885  */
2886 #if defined(_WIN32)
2887 # ifdef fileno
2888 #  undef fileno
2889 #  define fileno(a) (int)_fileno(a)
2890 # endif
2891
2892 # include <windows.h>
2893 # include <tchar.h>
2894
2895 static int WIN32_rename(const char *from, const char *to)
2896 {
2897     TCHAR *tfrom = NULL, *tto;
2898     DWORD err;
2899     int ret = 0;
2900
2901     if (sizeof(TCHAR) == 1) {
2902         tfrom = (TCHAR *)from;
2903         tto = (TCHAR *)to;
2904     } else {                    /* UNICODE path */
2905
2906         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2907         tfrom = (TCHAR *)malloc(sizeof(TCHAR) * (flen + tlen));
2908         if (tfrom == NULL)
2909             goto err;
2910         tto = tfrom + flen;
2911 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2912         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2913 # endif
2914             for (i = 0; i < flen; i++)
2915                 tfrom[i] = (TCHAR)from[i];
2916 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2917         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2918 # endif
2919             for (i = 0; i < tlen; i++)
2920                 tto[i] = (TCHAR)to[i];
2921     }
2922
2923     if (MoveFile(tfrom, tto))
2924         goto ok;
2925     err = GetLastError();
2926     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2927         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2928             goto ok;
2929         err = GetLastError();
2930     }
2931     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2932         errno = ENOENT;
2933     else if (err == ERROR_ACCESS_DENIED)
2934         errno = EACCES;
2935     else
2936         errno = EINVAL;         /* we could map more codes... */
2937  err:
2938     ret = -1;
2939  ok:
2940     if (tfrom != NULL && tfrom != (TCHAR *)from)
2941         free(tfrom);
2942     return ret;
2943 }
2944 #endif
2945
2946 /* app_tminterval section */
2947 #if defined(_WIN32)
2948 double app_tminterval(int stop, int usertime)
2949 {
2950     FILETIME now;
2951     double ret = 0;
2952     static ULARGE_INTEGER tmstart;
2953     static int warning = 1;
2954 # ifdef _WIN32_WINNT
2955     static HANDLE proc = NULL;
2956
2957     if (proc == NULL) {
2958         if (check_winnt())
2959             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2960                                GetCurrentProcessId());
2961         if (proc == NULL)
2962             proc = (HANDLE) - 1;
2963     }
2964
2965     if (usertime && proc != (HANDLE) - 1) {
2966         FILETIME junk;
2967         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2968     } else
2969 # endif
2970     {
2971         SYSTEMTIME systime;
2972
2973         if (usertime && warning) {
2974             BIO_printf(bio_err, "To get meaningful results, run "
2975                        "this program on idle system.\n");
2976             warning = 0;
2977         }
2978         GetSystemTime(&systime);
2979         SystemTimeToFileTime(&systime, &now);
2980     }
2981
2982     if (stop == TM_START) {
2983         tmstart.u.LowPart = now.dwLowDateTime;
2984         tmstart.u.HighPart = now.dwHighDateTime;
2985     } else {
2986         ULARGE_INTEGER tmstop;
2987
2988         tmstop.u.LowPart = now.dwLowDateTime;
2989         tmstop.u.HighPart = now.dwHighDateTime;
2990
2991         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2992     }
2993
2994     return (ret);
2995 }
2996
2997 #elif defined(OPENSSL_SYS_NETWARE)
2998 # include <time.h>
2999
3000 double app_tminterval(int stop, int usertime)
3001 {
3002     double ret = 0;
3003     static clock_t tmstart;
3004     static int warning = 1;
3005
3006     if (usertime && warning) {
3007         BIO_printf(bio_err, "To get meaningful results, run "
3008                    "this program on idle system.\n");
3009         warning = 0;
3010     }
3011
3012     if (stop == TM_START)
3013         tmstart = clock();
3014     else
3015         ret = (clock() - tmstart) / (double)CLOCKS_PER_SEC;
3016
3017     return (ret);
3018 }
3019
3020 #elif defined(OPENSSL_SYSTEM_VXWORKS)
3021 # include <time.h>
3022
3023 double app_tminterval(int stop, int usertime)
3024 {
3025     double ret = 0;
3026 # ifdef CLOCK_REALTIME
3027     static struct timespec tmstart;
3028     struct timespec now;
3029 # else
3030     static unsigned long tmstart;
3031     unsigned long now;
3032 # endif
3033     static int warning = 1;
3034
3035     if (usertime && warning) {
3036         BIO_printf(bio_err, "To get meaningful results, run "
3037                    "this program on idle system.\n");
3038         warning = 0;
3039     }
3040 # ifdef CLOCK_REALTIME
3041     clock_gettime(CLOCK_REALTIME, &now);
3042     if (stop == TM_START)
3043         tmstart = now;
3044     else
3045         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
3046                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
3047 # else
3048     now = tickGet();
3049     if (stop == TM_START)
3050         tmstart = now;
3051     else
3052         ret = (now - tmstart) / (double)sysClkRateGet();
3053 # endif
3054     return (ret);
3055 }
3056
3057 #elif defined(OPENSSL_SYSTEM_VMS)
3058 # include <time.h>
3059 # include <times.h>
3060
3061 double app_tminterval(int stop, int usertime)
3062 {
3063     static clock_t tmstart;
3064     double ret = 0;
3065     clock_t now;
3066 # ifdef __TMS
3067     struct tms rus;
3068
3069     now = times(&rus);
3070     if (usertime)
3071         now = rus.tms_utime;
3072 # else
3073     if (usertime)
3074         now = clock();          /* sum of user and kernel times */
3075     else {
3076         struct timeval tv;
3077         gettimeofday(&tv, NULL);
3078         now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
3079                         (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
3080             );
3081     }
3082 # endif
3083     if (stop == TM_START)
3084         tmstart = now;
3085     else
3086         ret = (now - tmstart) / (double)(CLK_TCK);
3087
3088     return (ret);
3089 }
3090
3091 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
3092 # include <sys/times.h>
3093
3094 double app_tminterval(int stop, int usertime)
3095 {
3096     double ret = 0;
3097     struct tms rus;
3098     clock_t now = times(&rus);
3099     static clock_t tmstart;
3100
3101     if (usertime)
3102         now = rus.tms_utime;
3103
3104     if (stop == TM_START)
3105         tmstart = now;
3106     else {
3107         long int tck = sysconf(_SC_CLK_TCK);
3108         ret = (now - tmstart) / (double)tck;
3109     }
3110
3111     return (ret);
3112 }
3113
3114 #else
3115 # include <sys/time.h>
3116 # include <sys/resource.h>
3117
3118 double app_tminterval(int stop, int usertime)
3119 {
3120     double ret = 0;
3121     struct rusage rus;
3122     struct timeval now;
3123     static struct timeval tmstart;
3124
3125     if (usertime)
3126         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
3127     else
3128         gettimeofday(&now, NULL);
3129
3130     if (stop == TM_START)
3131         tmstart = now;
3132     else
3133         ret = ((now.tv_sec + now.tv_usec * 1e-6)
3134                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
3135
3136     return ret;
3137 }
3138 #endif
3139
3140 /* app_isdir section */
3141 #ifdef _WIN32
3142 int app_isdir(const char *name)
3143 {
3144     HANDLE hList;
3145     WIN32_FIND_DATA FileData;
3146 # if defined(UNICODE) || defined(_UNICODE)
3147     size_t i, len_0 = strlen(name) + 1;
3148
3149     if (len_0 > sizeof(FileData.cFileName) / sizeof(FileData.cFileName[0]))
3150         return -1;
3151
3152 #  if !defined(_WIN32_WCE) || _WIN32_WCE>=101
3153     if (!MultiByteToWideChar
3154         (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
3155 #  endif
3156         for (i = 0; i < len_0; i++)
3157             FileData.cFileName[i] = (WCHAR)name[i];
3158
3159     hList = FindFirstFile(FileData.cFileName, &FileData);
3160 # else
3161     hList = FindFirstFile(name, &FileData);
3162 # endif
3163     if (hList == INVALID_HANDLE_VALUE)
3164         return -1;
3165     FindClose(hList);
3166     return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
3167 }
3168 #else
3169 # include <sys/stat.h>
3170 # ifndef S_ISDIR
3171 #  if defined(_S_IFMT) && defined(_S_IFDIR)
3172 #   define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
3173 #  else
3174 #   define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
3175 #  endif
3176 # endif
3177
3178 int app_isdir(const char *name)
3179 {
3180 # if defined(S_ISDIR)
3181     struct stat st;
3182
3183     if (stat(name, &st) == 0)
3184         return S_ISDIR(st.st_mode);
3185     else
3186         return -1;
3187 # else
3188     return -1;
3189 # endif
3190 }
3191 #endif
3192
3193 /* raw_read|write section */
3194 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
3195 int raw_read_stdin(void *buf, int siz)
3196 {
3197     DWORD n;
3198     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
3199         return (n);
3200     else
3201         return (-1);
3202 }
3203 #else
3204 int raw_read_stdin(void *buf, int siz)
3205 {
3206     return read(fileno(stdin), buf, siz);
3207 }
3208 #endif
3209
3210 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
3211 int raw_write_stdout(const void *buf, int siz)
3212 {
3213     DWORD n;
3214     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
3215         return (n);
3216     else
3217         return (-1);
3218 }
3219 #else
3220 int raw_write_stdout(const void *buf, int siz)
3221 {
3222     return write(fileno(stdout), buf, siz);
3223 }
3224 #endif