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