WinCE patches
[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 #include <stdio.h>
113 #include <stdlib.h>
114 #include <string.h>
115 #include <sys/types.h>
116 #include <sys/stat.h>
117 #include <ctype.h>
118 #include <openssl/err.h>
119 #include <openssl/x509.h>
120 #include <openssl/x509v3.h>
121 #include <openssl/pem.h>
122 #include <openssl/pkcs12.h>
123 #include <openssl/ui.h>
124 #include <openssl/safestack.h>
125 #include <openssl/engine.h>
126
127 #ifdef OPENSSL_SYS_WINDOWS
128 #define strcasecmp _stricmp
129 #else
130 #  ifdef NO_STRINGS_H
131     int strcasecmp();
132 #  else
133 #    include <strings.h>
134 #  endif /* NO_STRINGS_H */
135 #endif
136
137 #define NON_MAIN
138 #include "apps.h"
139 #undef NON_MAIN
140
141 #ifdef OPENSSL_SYS_WINDOWS
142 #  include "bss_file.c"
143 #endif
144
145 typedef struct {
146         char *name;
147         unsigned long flag;
148         unsigned long mask;
149 } NAME_EX_TBL;
150
151 static UI_METHOD *ui_method = NULL;
152
153 static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
154 static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
155
156 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
157 /* Looks like this stuff is worth moving into separate function */
158 static EVP_PKEY *
159 load_netscape_key(BIO *err, BIO *key, const char *file,
160                 const char *key_descrip, int format);
161 #endif
162
163 int app_init(long mesgwin);
164 #ifdef undef /* never finished - probably never will be :-) */
165 int args_from_file(char *file, int *argc, char **argv[])
166         {
167         FILE *fp;
168         int num,i;
169         unsigned int len;
170         static char *buf=NULL;
171         static char **arg=NULL;
172         char *p;
173         struct stat stbuf;
174
175         if (stat(file,&stbuf) < 0) return(0);
176
177         fp=fopen(file,"r");
178         if (fp == NULL)
179                 return(0);
180
181         *argc=0;
182         *argv=NULL;
183
184         len=(unsigned int)stbuf.st_size;
185         if (buf != NULL) OPENSSL_free(buf);
186         buf=(char *)OPENSSL_malloc(len+1);
187         if (buf == NULL) return(0);
188
189         len=fread(buf,1,len,fp);
190         if (len <= 1) return(0);
191         buf[len]='\0';
192
193         i=0;
194         for (p=buf; *p; p++)
195                 if (*p == '\n') i++;
196         if (arg != NULL) OPENSSL_free(arg);
197         arg=(char **)OPENSSL_malloc(sizeof(char *)*(i*2));
198
199         *argv=arg;
200         num=0;
201         p=buf;
202         for (;;)
203                 {
204                 if (!*p) break;
205                 if (*p == '#') /* comment line */
206                         {
207                         while (*p && (*p != '\n')) p++;
208                         continue;
209                         }
210                 /* else we have a line */
211                 *(arg++)=p;
212                 num++;
213                 while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
214                         p++;
215                 if (!*p) break;
216                 if (*p == '\n')
217                         {
218                         *(p++)='\0';
219                         continue;
220                         }
221                 /* else it is a tab or space */
222                 p++;
223                 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
224                         p++;
225                 if (!*p) break;
226                 if (*p == '\n')
227                         {
228                         p++;
229                         continue;
230                         }
231                 *(arg++)=p++;
232                 num++;
233                 while (*p && (*p != '\n')) p++;
234                 if (!*p) break;
235                 /* else *p == '\n' */
236                 *(p++)='\0';
237                 }
238         *argc=num;
239         return(1);
240         }
241 #endif
242
243 int str2fmt(char *s)
244         {
245         if      ((*s == 'D') || (*s == 'd'))
246                 return(FORMAT_ASN1);
247         else if ((*s == 'T') || (*s == 't'))
248                 return(FORMAT_TEXT);
249         else if ((*s == 'P') || (*s == 'p'))
250                 return(FORMAT_PEM);
251         else if ((*s == 'N') || (*s == 'n'))
252                 return(FORMAT_NETSCAPE);
253         else if ((*s == 'S') || (*s == 's'))
254                 return(FORMAT_SMIME);
255         else if ((*s == '1')
256                 || (strcmp(s,"PKCS12") == 0) || (strcmp(s,"pkcs12") == 0)
257                 || (strcmp(s,"P12") == 0) || (strcmp(s,"p12") == 0))
258                 return(FORMAT_PKCS12);
259         else if ((*s == 'E') || (*s == 'e'))
260                 return(FORMAT_ENGINE);
261         else
262                 return(FORMAT_UNDEF);
263         }
264
265 #if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
266 void program_name(char *in, char *out, int size)
267         {
268         int i,n;
269         char *p=NULL;
270
271         n=strlen(in);
272         /* find the last '/', '\' or ':' */
273         for (i=n-1; i>0; i--)
274                 {
275                 if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':'))
276                         {
277                         p= &(in[i+1]);
278                         break;
279                         }
280                 }
281         if (p == NULL)
282                 p=in;
283         n=strlen(p);
284         /* strip off trailing .exe if present. */
285         if ((n > 4) && (p[n-4] == '.') &&
286                 ((p[n-3] == 'e') || (p[n-3] == 'E')) &&
287                 ((p[n-2] == 'x') || (p[n-2] == 'X')) &&
288                 ((p[n-1] == 'e') || (p[n-1] == 'E')))
289                 n-=4;
290         if (n > size-1)
291                 n=size-1;
292
293         for (i=0; i<n; i++)
294                 {
295                 if ((p[i] >= 'A') && (p[i] <= 'Z'))
296                         out[i]=p[i]-'A'+'a';
297                 else
298                         out[i]=p[i];
299                 }
300         out[n]='\0';
301         }
302 #else
303 #ifdef OPENSSL_SYS_VMS
304 void program_name(char *in, char *out, int size)
305         {
306         char *p=in, *q;
307         char *chars=":]>";
308
309         while(*chars != '\0')
310                 {
311                 q=strrchr(p,*chars);
312                 if (q > p)
313                         p = q + 1;
314                 chars++;
315                 }
316
317         q=strrchr(p,'.');
318         if (q == NULL)
319                 q = p + strlen(p);
320         strncpy(out,p,size-1);
321         if (q-p >= size)
322                 {
323                 out[size-1]='\0';
324                 }
325         else
326                 {
327                 out[q-p]='\0';
328                 }
329         }
330 #else
331 void program_name(char *in, char *out, int size)
332         {
333         char *p;
334
335         p=strrchr(in,'/');
336         if (p != NULL)
337                 p++;
338         else
339                 p=in;
340         BUF_strlcpy(out,p,size);
341         }
342 #endif
343 #endif
344
345 #ifdef OPENSSL_SYS_WIN32
346 int WIN32_rename(char *from, char *to)
347         {
348 #ifndef OPENSSL_SYS_WINCE
349         /* Windows rename gives an error if 'to' exists, so delete it
350          * first and ignore file not found errror
351          */
352         if((remove(to) != 0) && (errno != ENOENT))
353                 return -1;
354 #undef rename
355         return rename(from, to);
356 #else
357         /* convert strings to UNICODE */
358         {
359         BOOL result = FALSE;
360         WCHAR* wfrom;
361         WCHAR* wto;
362         int i;
363         wfrom = malloc((strlen(from)+1)*2);
364         wto = malloc((strlen(to)+1)*2);
365         if (wfrom != NULL && wto != NULL)
366                 {
367                 for (i=0; i<(int)strlen(from)+1; i++)
368                         wfrom[i] = (short)from[i];
369                 for (i=0; i<(int)strlen(to)+1; i++)
370                         wto[i] = (short)to[i];
371                 result = MoveFile(wfrom, wto);
372                 }
373         if (wfrom != NULL)
374                 free(wfrom);
375         if (wto != NULL)
376                 free(wto);
377         return result;
378         }
379 #endif
380         }
381 #endif
382
383 #ifdef OPENSSL_SYS_VMS
384 int VMS_strcasecmp(const char *str1, const char *str2)
385         {
386         while (*str1 && *str2)
387                 {
388                 int res = toupper(*str1) - toupper(*str2);
389                 if (res) return res < 0 ? -1 : 1;
390                 }
391         if (*str1)
392                 return 1;
393         if (*str2)
394                 return -1;
395         return 0;
396         }
397 #endif
398
399 int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
400         {
401         int num,len,i;
402         char *p;
403
404         *argc=0;
405         *argv=NULL;
406
407         len=strlen(buf);
408         i=0;
409         if (arg->count == 0)
410                 {
411                 arg->count=20;
412                 arg->data=(char **)OPENSSL_malloc(sizeof(char *)*arg->count);
413                 }
414         for (i=0; i<arg->count; i++)
415                 arg->data[i]=NULL;
416
417         num=0;
418         p=buf;
419         for (;;)
420                 {
421                 /* first scan over white space */
422                 if (!*p) break;
423                 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
424                         p++;
425                 if (!*p) break;
426
427                 /* The start of something good :-) */
428                 if (num >= arg->count)
429                         {
430                         arg->count+=20;
431                         arg->data=(char **)OPENSSL_realloc(arg->data,
432                                 sizeof(char *)*arg->count);
433                         if (argc == 0) return(0);
434                         }
435                 arg->data[num++]=p;
436
437                 /* now look for the end of this */
438                 if ((*p == '\'') || (*p == '\"')) /* scan for closing quote */
439                         {
440                         i= *(p++);
441                         arg->data[num-1]++; /* jump over quote */
442                         while (*p && (*p != i))
443                                 p++;
444                         *p='\0';
445                         }
446                 else
447                         {
448                         while (*p && ((*p != ' ') &&
449                                 (*p != '\t') && (*p != '\n')))
450                                 p++;
451
452                         if (*p == '\0')
453                                 p--;
454                         else
455                                 *p='\0';
456                         }
457                 p++;
458                 }
459         *argc=num;
460         *argv=arg->data;
461         return(1);
462         }
463
464 #ifndef APP_INIT
465 int app_init(long mesgwin)
466         {
467         return(1);
468         }
469 #endif
470
471
472 int dump_cert_text (BIO *out, X509 *x)
473 {
474         char *p;
475
476         p=X509_NAME_oneline(X509_get_subject_name(x),NULL,0);
477         BIO_puts(out,"subject=");
478         BIO_puts(out,p);
479         OPENSSL_free(p);
480
481         p=X509_NAME_oneline(X509_get_issuer_name(x),NULL,0);
482         BIO_puts(out,"\nissuer=");
483         BIO_puts(out,p);
484         BIO_puts(out,"\n");
485         OPENSSL_free(p);
486
487         return 0;
488 }
489
490 static int ui_open(UI *ui)
491         {
492         return UI_method_get_opener(UI_OpenSSL())(ui);
493         }
494 static int ui_read(UI *ui, UI_STRING *uis)
495         {
496         if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
497                 && UI_get0_user_data(ui))
498                 {
499                 switch(UI_get_string_type(uis))
500                         {
501                 case UIT_PROMPT:
502                 case UIT_VERIFY:
503                         {
504                         const char *password =
505                                 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
506                         if (password[0] != '\0')
507                                 {
508                                 UI_set_result(ui, uis, password);
509                                 return 1;
510                                 }
511                         }
512                 default:
513                         break;
514                         }
515                 }
516         return UI_method_get_reader(UI_OpenSSL())(ui, uis);
517         }
518 static int ui_write(UI *ui, UI_STRING *uis)
519         {
520         if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
521                 && UI_get0_user_data(ui))
522                 {
523                 switch(UI_get_string_type(uis))
524                         {
525                 case UIT_PROMPT:
526                 case UIT_VERIFY:
527                         {
528                         const char *password =
529                                 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
530                         if (password[0] != '\0')
531                                 return 1;
532                         }
533                 default:
534                         break;
535                         }
536                 }
537         return UI_method_get_writer(UI_OpenSSL())(ui, uis);
538         }
539 static int ui_close(UI *ui)
540         {
541         return UI_method_get_closer(UI_OpenSSL())(ui);
542         }
543 int setup_ui_method(void)
544         {
545         ui_method = UI_create_method("OpenSSL application user interface");
546         UI_method_set_opener(ui_method, ui_open);
547         UI_method_set_reader(ui_method, ui_read);
548         UI_method_set_writer(ui_method, ui_write);
549         UI_method_set_closer(ui_method, ui_close);
550         return 0;
551         }
552 void destroy_ui_method(void)
553         {
554         if(ui_method)
555                 {
556                 UI_destroy_method(ui_method);
557                 ui_method = NULL;
558                 }
559         }
560 int password_callback(char *buf, int bufsiz, int verify,
561         PW_CB_DATA *cb_tmp)
562         {
563         UI *ui = NULL;
564         int res = 0;
565         const char *prompt_info = NULL;
566         const char *password = NULL;
567         PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
568
569         if (cb_data)
570                 {
571                 if (cb_data->password)
572                         password = cb_data->password;
573                 if (cb_data->prompt_info)
574                         prompt_info = cb_data->prompt_info;
575                 }
576
577         if (password)
578                 {
579                 res = strlen(password);
580                 if (res > bufsiz)
581                         res = bufsiz;
582                 memcpy(buf, password, res);
583                 return res;
584                 }
585
586         ui = UI_new_method(ui_method);
587         if (ui)
588                 {
589                 int ok = 0;
590                 char *buff = NULL;
591                 int ui_flags = 0;
592                 char *prompt = NULL;
593
594                 prompt = UI_construct_prompt(ui, "pass phrase",
595                         cb_data->prompt_info);
596
597                 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
598                 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
599
600                 if (ok >= 0)
601                         ok = UI_add_input_string(ui,prompt,ui_flags,buf,
602                                 PW_MIN_LENGTH,BUFSIZ-1);
603                 if (ok >= 0 && verify)
604                         {
605                         buff = (char *)OPENSSL_malloc(bufsiz);
606                         ok = UI_add_verify_string(ui,prompt,ui_flags,buff,
607                                 PW_MIN_LENGTH,BUFSIZ-1, buf);
608                         }
609                 if (ok >= 0)
610                         do
611                                 {
612                                 ok = UI_process(ui);
613                                 }
614                         while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
615
616                 if (buff)
617                         {
618                         memset(buff,0,(unsigned int)bufsiz);
619                         OPENSSL_free(buff);
620                         }
621
622                 if (ok >= 0)
623                         res = strlen(buf);
624                 if (ok == -1)
625                         {
626                         BIO_printf(bio_err, "User interface error\n");
627                         ERR_print_errors(bio_err);
628                         memset(buf,0,(unsigned int)bufsiz);
629                         res = 0;
630                         }
631                 if (ok == -2)
632                         {
633                         BIO_printf(bio_err,"aborted!\n");
634                         memset(buf,0,(unsigned int)bufsiz);
635                         res = 0;
636                         }
637                 UI_free(ui);
638                 OPENSSL_free(prompt);
639                 }
640         return res;
641         }
642
643 static char *app_get_pass(BIO *err, char *arg, int keepbio);
644
645 int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
646 {
647         int same;
648         if(!arg2 || !arg1 || strcmp(arg1, arg2)) same = 0;
649         else same = 1;
650         if(arg1) {
651                 *pass1 = app_get_pass(err, arg1, same);
652                 if(!*pass1) return 0;
653         } else if(pass1) *pass1 = NULL;
654         if(arg2) {
655                 *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
656                 if(!*pass2) return 0;
657         } else if(pass2) *pass2 = NULL;
658         return 1;
659 }
660
661 static char *app_get_pass(BIO *err, char *arg, int keepbio)
662 {
663         char *tmp, tpass[APP_PASS_LEN];
664         static BIO *pwdbio = NULL;
665         int i;
666         if(!strncmp(arg, "pass:", 5)) return BUF_strdup(arg + 5);
667         if(!strncmp(arg, "env:", 4)) {
668                 tmp = getenv(arg + 4);
669                 if(!tmp) {
670                         BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
671                         return NULL;
672                 }
673                 return BUF_strdup(tmp);
674         }
675         if(!keepbio || !pwdbio) {
676                 if(!strncmp(arg, "file:", 5)) {
677                         pwdbio = BIO_new_file(arg + 5, "r");
678                         if(!pwdbio) {
679                                 BIO_printf(err, "Can't open file %s\n", arg + 5);
680                                 return NULL;
681                         }
682                 } else if(!strncmp(arg, "fd:", 3)) {
683                         BIO *btmp;
684                         i = atoi(arg + 3);
685                         if(i >= 0) pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
686                         if((i < 0) || !pwdbio) {
687                                 BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
688                                 return NULL;
689                         }
690                         /* Can't do BIO_gets on an fd BIO so add a buffering BIO */
691                         btmp = BIO_new(BIO_f_buffer());
692                         pwdbio = BIO_push(btmp, pwdbio);
693                 } else if(!strcmp(arg, "stdin")) {
694                         pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
695                         if(!pwdbio) {
696                                 BIO_printf(err, "Can't open BIO for stdin\n");
697                                 return NULL;
698                         }
699                 } else {
700                         BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
701                         return NULL;
702                 }
703         }
704         i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
705         if(keepbio != 1) {
706                 BIO_free_all(pwdbio);
707                 pwdbio = NULL;
708         }
709         if(i <= 0) {
710                 BIO_printf(err, "Error reading password from BIO\n");
711                 return NULL;
712         }
713         tmp = strchr(tpass, '\n');
714         if(tmp) *tmp = 0;
715         return BUF_strdup(tpass);
716 }
717
718 int add_oid_section(BIO *err, CONF *conf)
719 {       
720         char *p;
721         STACK_OF(CONF_VALUE) *sktmp;
722         CONF_VALUE *cnf;
723         int i;
724         if(!(p=NCONF_get_string(conf,NULL,"oid_section")))
725                 {
726                 ERR_clear_error();
727                 return 1;
728                 }
729         if(!(sktmp = NCONF_get_section(conf, p))) {
730                 BIO_printf(err, "problem loading oid section %s\n", p);
731                 return 0;
732         }
733         for(i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
734                 cnf = sk_CONF_VALUE_value(sktmp, i);
735                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
736                         BIO_printf(err, "problem creating object %s=%s\n",
737                                                          cnf->name, cnf->value);
738                         return 0;
739                 }
740         }
741         return 1;
742 }
743
744 X509 *load_cert(BIO *err, const char *file, int format,
745         const char *pass, ENGINE *e, const char *cert_descrip)
746         {
747         ASN1_HEADER *ah=NULL;
748         BUF_MEM *buf=NULL;
749         X509 *x=NULL;
750         BIO *cert;
751
752         if ((cert=BIO_new(BIO_s_file())) == NULL)
753                 {
754                 ERR_print_errors(err);
755                 goto end;
756                 }
757
758         if (file == NULL)
759                 {
760                 setvbuf(stdin, NULL, _IONBF, 0);
761                 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
762                 }
763         else
764                 {
765                 if (BIO_read_filename(cert,file) <= 0)
766                         {
767                         BIO_printf(err, "Error opening %s %s\n",
768                                 cert_descrip, file);
769                         ERR_print_errors(err);
770                         goto end;
771                         }
772                 }
773
774         if      (format == FORMAT_ASN1)
775                 x=d2i_X509_bio(cert,NULL);
776         else if (format == FORMAT_NETSCAPE)
777                 {
778                 unsigned char *p,*op;
779                 int size=0,i;
780
781                 /* We sort of have to do it this way because it is sort of nice
782                  * to read the header first and check it, then
783                  * try to read the certificate */
784                 buf=BUF_MEM_new();
785                 for (;;)
786                         {
787                         if ((buf == NULL) || (!BUF_MEM_grow(buf,size+1024*10)))
788                                 goto end;
789                         i=BIO_read(cert,&(buf->data[size]),1024*10);
790                         size+=i;
791                         if (i == 0) break;
792                         if (i < 0)
793                                 {
794                                 perror("reading certificate");
795                                 goto end;
796                                 }
797                         }
798                 p=(unsigned char *)buf->data;
799                 op=p;
800
801                 /* First load the header */
802                 if ((ah=d2i_ASN1_HEADER(NULL,&p,(long)size)) == NULL)
803                         goto end;
804                 if ((ah->header == NULL) || (ah->header->data == NULL) ||
805                         (strncmp(NETSCAPE_CERT_HDR,(char *)ah->header->data,
806                         ah->header->length) != 0))
807                         {
808                         BIO_printf(err,"Error reading header on certificate\n");
809                         goto end;
810                         }
811                 /* header is ok, so now read the object */
812                 p=op;
813                 ah->meth=X509_asn1_meth();
814                 if ((ah=d2i_ASN1_HEADER(&ah,&p,(long)size)) == NULL)
815                         goto end;
816                 x=(X509 *)ah->data;
817                 ah->data=NULL;
818                 }
819         else if (format == FORMAT_PEM)
820                 x=PEM_read_bio_X509_AUX(cert,NULL,
821                         (pem_password_cb *)password_callback, NULL);
822         else if (format == FORMAT_PKCS12)
823                 {
824                 PKCS12 *p12 = d2i_PKCS12_bio(cert, NULL);
825
826                 PKCS12_parse(p12, NULL, NULL, &x, NULL);
827                 PKCS12_free(p12);
828                 p12 = NULL;
829                 }
830         else    {
831                 BIO_printf(err,"bad input format specified for %s\n",
832                         cert_descrip);
833                 goto end;
834                 }
835 end:
836         if (x == NULL)
837                 {
838                 BIO_printf(err,"unable to load certificate\n");
839                 ERR_print_errors(err);
840                 }
841         if (ah != NULL) ASN1_HEADER_free(ah);
842         if (cert != NULL) BIO_free(cert);
843         if (buf != NULL) BUF_MEM_free(buf);
844         return(x);
845         }
846
847 EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
848         const char *pass, ENGINE *e, const char *key_descrip)
849         {
850         BIO *key=NULL;
851         EVP_PKEY *pkey=NULL;
852         PW_CB_DATA cb_data;
853
854         cb_data.password = pass;
855         cb_data.prompt_info = file;
856
857         if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
858                 {
859                 BIO_printf(err,"no keyfile specified\n");
860                 goto end;
861                 }
862         if (format == FORMAT_ENGINE)
863                 {
864                 if (!e)
865                         BIO_printf(bio_err,"no engine specified\n");
866                 else
867                         pkey = ENGINE_load_private_key(e, file,
868                                 ui_method, &cb_data);
869                 goto end;
870                 }
871         key=BIO_new(BIO_s_file());
872         if (key == NULL)
873                 {
874                 ERR_print_errors(err);
875                 goto end;
876                 }
877         if (file == NULL && maybe_stdin)
878                 {
879                 setvbuf(stdin, NULL, _IONBF, 0);
880                 BIO_set_fp(key,stdin,BIO_NOCLOSE);
881                 }
882         else
883                 if (BIO_read_filename(key,file) <= 0)
884                         {
885                         BIO_printf(err, "Error opening %s %s\n",
886                                 key_descrip, file);
887                         ERR_print_errors(err);
888                         goto end;
889                         }
890         if (format == FORMAT_ASN1)
891                 {
892                 pkey=d2i_PrivateKey_bio(key, NULL);
893                 }
894         else if (format == FORMAT_PEM)
895                 {
896                 pkey=PEM_read_bio_PrivateKey(key,NULL,
897                         (pem_password_cb *)password_callback, &cb_data);
898                 }
899 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
900         else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
901                 pkey = load_netscape_key(err, key, file, key_descrip, format);
902 #endif
903         else if (format == FORMAT_PKCS12)
904                 {
905                 PKCS12 *p12 = d2i_PKCS12_bio(key, NULL);
906
907                 PKCS12_parse(p12, pass, &pkey, NULL, NULL);
908                 PKCS12_free(p12);
909                 p12 = NULL;
910                 }
911         else
912                 {
913                 BIO_printf(err,"bad input format specified for key file\n");
914                 goto end;
915                 }
916  end:
917         if (key != NULL) BIO_free(key);
918         if (pkey == NULL)
919                 BIO_printf(err,"unable to load %s\n", key_descrip);
920         return(pkey);
921         }
922
923 EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
924         const char *pass, ENGINE *e, const char *key_descrip)
925         {
926         BIO *key=NULL;
927         EVP_PKEY *pkey=NULL;
928         PW_CB_DATA cb_data;
929
930         cb_data.password = pass;
931         cb_data.prompt_info = file;
932
933         if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
934                 {
935                 BIO_printf(err,"no keyfile specified\n");
936                 goto end;
937                 }
938         if (format == FORMAT_ENGINE)
939                 {
940                 if (!e)
941                         BIO_printf(bio_err,"no engine specified\n");
942                 else
943                         pkey = ENGINE_load_public_key(e, file,
944                                 ui_method, &cb_data);
945                 goto end;
946                 }
947         key=BIO_new(BIO_s_file());
948         if (key == NULL)
949                 {
950                 ERR_print_errors(err);
951                 goto end;
952                 }
953         if (file == NULL && maybe_stdin)
954                 {
955                 setvbuf(stdin, NULL, _IONBF, 0);
956                 BIO_set_fp(key,stdin,BIO_NOCLOSE);
957                 }
958         else
959                 if (BIO_read_filename(key,file) <= 0)
960                         {
961                         BIO_printf(err, "Error opening %s %s\n",
962                                 key_descrip, file);
963                         ERR_print_errors(err);
964                         goto end;
965                 }
966         if (format == FORMAT_ASN1)
967                 {
968                 pkey=d2i_PUBKEY_bio(key, NULL);
969                 }
970         else if (format == FORMAT_PEM)
971                 {
972                 pkey=PEM_read_bio_PUBKEY(key,NULL,
973                         (pem_password_cb *)password_callback, &cb_data);
974                 }
975 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
976         else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
977                 pkey = load_netscape_key(err, key, file, key_descrip, format);
978 #endif
979         else
980                 {
981                 BIO_printf(err,"bad input format specified for key file\n");
982                 goto end;
983                 }
984  end:
985         if (key != NULL) BIO_free(key);
986         if (pkey == NULL)
987                 BIO_printf(err,"unable to load %s\n", key_descrip);
988         return(pkey);
989         }
990
991 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
992 static EVP_PKEY *
993 load_netscape_key(BIO *err, BIO *key, const char *file,
994                 const char *key_descrip, int format)
995         {
996         EVP_PKEY *pkey;
997         BUF_MEM *buf;
998         RSA     *rsa;
999         const unsigned char *p;
1000         int size, i;
1001
1002         buf=BUF_MEM_new();
1003         pkey = EVP_PKEY_new();
1004         size = 0;
1005         if (buf == NULL || pkey == NULL)
1006                 goto error;
1007         for (;;)
1008                 {
1009                 if (!BUF_MEM_grow_clean(buf,size+1024*10))
1010                         goto error;
1011                 i = BIO_read(key, &(buf->data[size]), 1024*10);
1012                 size += i;
1013                 if (i == 0)
1014                         break;
1015                 if (i < 0)
1016                         {
1017                                 BIO_printf(err, "Error reading %s %s",
1018                                         key_descrip, file);
1019                                 goto error;
1020                         }
1021                 }
1022         p=(unsigned char *)buf->data;
1023         rsa = d2i_RSA_NET(NULL,&p,(long)size,NULL,
1024                 (format == FORMAT_IISSGC ? 1 : 0));
1025         if (rsa == NULL)
1026                 goto error;
1027         BUF_MEM_free(buf);
1028         EVP_PKEY_set1_RSA(pkey, rsa);
1029         return pkey;
1030 error:
1031         BUF_MEM_free(buf);
1032         EVP_PKEY_free(pkey);
1033         return NULL;
1034         }
1035 #endif /* ndef OPENSSL_NO_RC4 */
1036
1037 STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
1038         const char *pass, ENGINE *e, const char *cert_descrip)
1039         {
1040         BIO *certs;
1041         int i;
1042         STACK_OF(X509) *othercerts = NULL;
1043         STACK_OF(X509_INFO) *allcerts = NULL;
1044         X509_INFO *xi;
1045         PW_CB_DATA cb_data;
1046
1047         cb_data.password = pass;
1048         cb_data.prompt_info = file;
1049
1050         if((certs = BIO_new(BIO_s_file())) == NULL)
1051                 {
1052                 ERR_print_errors(err);
1053                 goto end;
1054                 }
1055
1056         if (file == NULL)
1057                 BIO_set_fp(certs,stdin,BIO_NOCLOSE);
1058         else
1059                 {
1060                 if (BIO_read_filename(certs,file) <= 0)
1061                         {
1062                         BIO_printf(err, "Error opening %s %s\n",
1063                                 cert_descrip, file);
1064                         ERR_print_errors(err);
1065                         goto end;
1066                         }
1067                 }
1068
1069         if      (format == FORMAT_PEM)
1070                 {
1071                 othercerts = sk_X509_new_null();
1072                 if(!othercerts)
1073                         {
1074                         sk_X509_free(othercerts);
1075                         othercerts = NULL;
1076                         goto end;
1077                         }
1078                 allcerts = PEM_X509_INFO_read_bio(certs, NULL,
1079                                 (pem_password_cb *)password_callback, &cb_data);
1080                 for(i = 0; i < sk_X509_INFO_num(allcerts); i++)
1081                         {
1082                         xi = sk_X509_INFO_value (allcerts, i);
1083                         if (xi->x509)
1084                                 {
1085                                 sk_X509_push(othercerts, xi->x509);
1086                                 xi->x509 = NULL;
1087                                 }
1088                         }
1089                 goto end;
1090                 }
1091         else    {
1092                 BIO_printf(err,"bad input format specified for %s\n",
1093                         cert_descrip);
1094                 goto end;
1095                 }
1096 end:
1097         if (othercerts == NULL)
1098                 {
1099                 BIO_printf(err,"unable to load certificates\n");
1100                 ERR_print_errors(err);
1101                 }
1102         if (allcerts) sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
1103         if (certs != NULL) BIO_free(certs);
1104         return(othercerts);
1105         }
1106
1107
1108 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
1109 /* Return error for unknown extensions */
1110 #define X509V3_EXT_DEFAULT              0
1111 /* Print error for unknown extensions */
1112 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
1113 /* ASN1 parse unknown extensions */
1114 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
1115 /* BIO_dump unknown extensions */
1116 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
1117
1118 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1119                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1120
1121 int set_cert_ex(unsigned long *flags, const char *arg)
1122 {
1123         static const NAME_EX_TBL cert_tbl[] = {
1124                 { "compatible", X509_FLAG_COMPAT, 0xffffffffl},
1125                 { "ca_default", X509_FLAG_CA, 0xffffffffl},
1126                 { "no_header", X509_FLAG_NO_HEADER, 0},
1127                 { "no_version", X509_FLAG_NO_VERSION, 0},
1128                 { "no_serial", X509_FLAG_NO_SERIAL, 0},
1129                 { "no_signame", X509_FLAG_NO_SIGNAME, 0},
1130                 { "no_validity", X509_FLAG_NO_VALIDITY, 0},
1131                 { "no_subject", X509_FLAG_NO_SUBJECT, 0},
1132                 { "no_issuer", X509_FLAG_NO_ISSUER, 0},
1133                 { "no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1134                 { "no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1135                 { "no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1136                 { "no_aux", X509_FLAG_NO_AUX, 0},
1137                 { "no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1138                 { "ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1139                 { "ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1140                 { "ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1141                 { "ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1142                 { NULL, 0, 0}
1143         };
1144         return set_multi_opts(flags, arg, cert_tbl);
1145 }
1146
1147 int set_name_ex(unsigned long *flags, const char *arg)
1148 {
1149         static const NAME_EX_TBL ex_tbl[] = {
1150                 { "esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1151                 { "esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1152                 { "esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1153                 { "use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1154                 { "utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1155                 { "ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1156                 { "show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1157                 { "dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1158                 { "dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1159                 { "dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1160                 { "compat", XN_FLAG_COMPAT, 0xffffffffL},
1161                 { "sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1162                 { "sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1163                 { "sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1164                 { "sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1165                 { "dn_rev", XN_FLAG_DN_REV, 0},
1166                 { "nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1167                 { "sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1168                 { "lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1169                 { "align", XN_FLAG_FN_ALIGN, 0},
1170                 { "oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1171                 { "space_eq", XN_FLAG_SPC_EQ, 0},
1172                 { "dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1173                 { "RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1174                 { "oneline", XN_FLAG_ONELINE, 0xffffffffL},
1175                 { "multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1176                 { "ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1177                 { NULL, 0, 0}
1178         };
1179         return set_multi_opts(flags, arg, ex_tbl);
1180 }
1181
1182 int set_ext_copy(int *copy_type, const char *arg)
1183 {
1184         if (!strcasecmp(arg, "none"))
1185                 *copy_type = EXT_COPY_NONE;
1186         else if (!strcasecmp(arg, "copy"))
1187                 *copy_type = EXT_COPY_ADD;
1188         else if (!strcasecmp(arg, "copyall"))
1189                 *copy_type = EXT_COPY_ALL;
1190         else
1191                 return 0;
1192         return 1;
1193 }
1194
1195 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1196 {
1197         STACK_OF(X509_EXTENSION) *exts = NULL;
1198         X509_EXTENSION *ext, *tmpext;
1199         ASN1_OBJECT *obj;
1200         int i, idx, ret = 0;
1201         if (!x || !req || (copy_type == EXT_COPY_NONE))
1202                 return 1;
1203         exts = X509_REQ_get_extensions(req);
1204
1205         for(i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1206                 ext = sk_X509_EXTENSION_value(exts, i);
1207                 obj = X509_EXTENSION_get_object(ext);
1208                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1209                 /* Does extension exist? */
1210                 if (idx != -1) {
1211                         /* If normal copy don't override existing extension */
1212                         if (copy_type == EXT_COPY_ADD)
1213                                 continue;
1214                         /* Delete all extensions of same type */
1215                         do {
1216                                 tmpext = X509_get_ext(x, idx);
1217                                 X509_delete_ext(x, idx);
1218                                 X509_EXTENSION_free(tmpext);
1219                                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1220                         } while (idx != -1);
1221                 }
1222                 if (!X509_add_ext(x, ext, -1))
1223                         goto end;
1224         }
1225
1226         ret = 1;
1227
1228         end:
1229
1230         sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1231
1232         return ret;
1233 }
1234                 
1235                 
1236                         
1237
1238 static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1239 {
1240         STACK_OF(CONF_VALUE) *vals;
1241         CONF_VALUE *val;
1242         int i, ret = 1;
1243         if(!arg) return 0;
1244         vals = X509V3_parse_list(arg);
1245         for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1246                 val = sk_CONF_VALUE_value(vals, i);
1247                 if (!set_table_opts(flags, val->name, in_tbl))
1248                         ret = 0;
1249         }
1250         sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1251         return ret;
1252 }
1253
1254 static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1255 {
1256         char c;
1257         const NAME_EX_TBL *ptbl;
1258         c = arg[0];
1259
1260         if(c == '-') {
1261                 c = 0;
1262                 arg++;
1263         } else if (c == '+') {
1264                 c = 1;
1265                 arg++;
1266         } else c = 1;
1267
1268         for(ptbl = in_tbl; ptbl->name; ptbl++) {
1269                 if(!strcasecmp(arg, ptbl->name)) {
1270                         *flags &= ~ptbl->mask;
1271                         if(c) *flags |= ptbl->flag;
1272                         else *flags &= ~ptbl->flag;
1273                         return 1;
1274                 }
1275         }
1276         return 0;
1277 }
1278
1279 void print_name(BIO *out, char *title, X509_NAME *nm, unsigned long lflags)
1280 {
1281         char *buf;
1282         char mline = 0;
1283         int indent = 0;
1284
1285         if(title) BIO_puts(out, title);
1286         if((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1287                 mline = 1;
1288                 indent = 4;
1289         }
1290         if(lflags == XN_FLAG_COMPAT) {
1291                 buf = X509_NAME_oneline(nm, 0, 0);
1292                 BIO_puts(out, buf);
1293                 BIO_puts(out, "\n");
1294                 OPENSSL_free(buf);
1295         } else {
1296                 if(mline) BIO_puts(out, "\n");
1297                 X509_NAME_print_ex(out, nm, indent, lflags);
1298                 BIO_puts(out, "\n");
1299         }
1300 }
1301
1302 X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
1303 {
1304         X509_STORE *store;
1305         X509_LOOKUP *lookup;
1306         if(!(store = X509_STORE_new())) goto end;
1307         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
1308         if (lookup == NULL) goto end;
1309         if (CAfile) {
1310                 if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
1311                         BIO_printf(bp, "Error loading file %s\n", CAfile);
1312                         goto end;
1313                 }
1314         } else X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
1315                 
1316         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
1317         if (lookup == NULL) goto end;
1318         if (CApath) {
1319                 if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
1320                         BIO_printf(bp, "Error loading directory %s\n", CApath);
1321                         goto end;
1322                 }
1323         } else X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
1324
1325         ERR_clear_error();
1326         return store;
1327         end:
1328         X509_STORE_free(store);
1329         return NULL;
1330 }
1331
1332 /* Try to load an engine in a shareable library */
1333 static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
1334         {
1335         ENGINE *e = ENGINE_by_id("dynamic");
1336         if (e)
1337                 {
1338                 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1339                         || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
1340                         {
1341                         ENGINE_free(e);
1342                         e = NULL;
1343                         }
1344                 }
1345         return e;
1346         }
1347
1348 ENGINE *setup_engine(BIO *err, const char *engine, int debug)
1349         {
1350         ENGINE *e = NULL;
1351
1352         if (engine)
1353                 {
1354                 if(strcmp(engine, "auto") == 0)
1355                         {
1356                         BIO_printf(err,"enabling auto ENGINE support\n");
1357                         ENGINE_register_all_complete();
1358                         return NULL;
1359                         }
1360                 if((e = ENGINE_by_id(engine)) == NULL
1361                         && (e = try_load_engine(err, engine, debug)) == NULL)
1362                         {
1363                         BIO_printf(err,"invalid engine \"%s\"\n", engine);
1364                         ERR_print_errors(err);
1365                         return NULL;
1366                         }
1367                 if (debug)
1368                         {
1369                         ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM,
1370                                 0, err, 0);
1371                         }
1372                 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1373                 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
1374                         {
1375                         BIO_printf(err,"can't use that engine\n");
1376                         ERR_print_errors(err);
1377                         ENGINE_free(e);
1378                         return NULL;
1379                         }
1380
1381                 BIO_printf(err,"engine \"%s\" set.\n", ENGINE_get_id(e));
1382
1383                 /* Free our "structural" reference. */
1384                 ENGINE_free(e);
1385                 }
1386         return e;
1387         }
1388
1389 int load_config(BIO *err, CONF *cnf)
1390         {
1391         if (!cnf)
1392                 cnf = config;
1393         if (!cnf)
1394                 return 1;
1395
1396         OPENSSL_load_builtin_modules();
1397
1398         if (CONF_modules_load(cnf, NULL, 0) <= 0)
1399                 {
1400                 BIO_printf(err, "Error configuring OpenSSL\n");
1401                 ERR_print_errors(err);
1402                 return 0;
1403                 }
1404         return 1;
1405         }
1406
1407 char *make_config_name()
1408         {
1409         const char *t=X509_get_default_cert_area();
1410         char *p;
1411
1412         p=OPENSSL_malloc(strlen(t)+strlen(OPENSSL_CONF)+2);
1413         strcpy(p,t);
1414 #ifndef OPENSSL_SYS_VMS
1415         strcat(p,"/");
1416 #endif
1417         strcat(p,OPENSSL_CONF);
1418
1419         return p;
1420         }