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