1bcebc749af5c13c5730eb2d23f7c8bb07a65554
[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 #include <openssl/rsa.h>
129 #include <openssl/bn.h>
130
131 #define NON_MAIN
132 #include "apps.h"
133 #undef NON_MAIN
134
135 typedef struct {
136         char *name;
137         unsigned long flag;
138         unsigned long mask;
139 } NAME_EX_TBL;
140
141 static UI_METHOD *ui_method = NULL;
142
143 static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
144 static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
145
146 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
147 /* Looks like this stuff is worth moving into separate function */
148 static EVP_PKEY *
149 load_netscape_key(BIO *err, BIO *key, const char *file,
150                 const char *key_descrip, int format);
151 #endif
152
153 int app_init(long mesgwin);
154 #ifdef undef /* never finished - probably never will be :-) */
155 int args_from_file(char *file, int *argc, char **argv[])
156         {
157         FILE *fp;
158         int num,i;
159         unsigned int len;
160         static char *buf=NULL;
161         static char **arg=NULL;
162         char *p;
163         struct stat stbuf;
164
165         if (stat(file,&stbuf) < 0) return(0);
166
167         fp=fopen(file,"r");
168         if (fp == NULL)
169                 return(0);
170
171         *argc=0;
172         *argv=NULL;
173
174         len=(unsigned int)stbuf.st_size;
175         if (buf != NULL) OPENSSL_free(buf);
176         buf=(char *)OPENSSL_malloc(len+1);
177         if (buf == NULL) return(0);
178
179         len=fread(buf,1,len,fp);
180         if (len <= 1) return(0);
181         buf[len]='\0';
182
183         i=0;
184         for (p=buf; *p; p++)
185                 if (*p == '\n') i++;
186         if (arg != NULL) OPENSSL_free(arg);
187         arg=(char **)OPENSSL_malloc(sizeof(char *)*(i*2));
188
189         *argv=arg;
190         num=0;
191         p=buf;
192         for (;;)
193                 {
194                 if (!*p) break;
195                 if (*p == '#') /* comment line */
196                         {
197                         while (*p && (*p != '\n')) p++;
198                         continue;
199                         }
200                 /* else we have a line */
201                 *(arg++)=p;
202                 num++;
203                 while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
204                         p++;
205                 if (!*p) break;
206                 if (*p == '\n')
207                         {
208                         *(p++)='\0';
209                         continue;
210                         }
211                 /* else it is a tab or space */
212                 p++;
213                 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
214                         p++;
215                 if (!*p) break;
216                 if (*p == '\n')
217                         {
218                         p++;
219                         continue;
220                         }
221                 *(arg++)=p++;
222                 num++;
223                 while (*p && (*p != '\n')) p++;
224                 if (!*p) break;
225                 /* else *p == '\n' */
226                 *(p++)='\0';
227                 }
228         *argc=num;
229         return(1);
230         }
231 #endif
232
233 int str2fmt(char *s)
234         {
235         if      ((*s == 'D') || (*s == 'd'))
236                 return(FORMAT_ASN1);
237         else if ((*s == 'T') || (*s == 't'))
238                 return(FORMAT_TEXT);
239         else if ((*s == 'P') || (*s == 'p'))
240                 return(FORMAT_PEM);
241         else if ((*s == 'N') || (*s == 'n'))
242                 return(FORMAT_NETSCAPE);
243         else if ((*s == 'S') || (*s == 's'))
244                 return(FORMAT_SMIME);
245         else if ((*s == '1')
246                 || (strcmp(s,"PKCS12") == 0) || (strcmp(s,"pkcs12") == 0)
247                 || (strcmp(s,"P12") == 0) || (strcmp(s,"p12") == 0))
248                 return(FORMAT_PKCS12);
249         else if ((*s == 'E') || (*s == 'e'))
250                 return(FORMAT_ENGINE);
251         else
252                 return(FORMAT_UNDEF);
253         }
254
255 #if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_NETWARE)
256 void program_name(char *in, char *out, int size)
257         {
258         int i,n;
259         char *p=NULL;
260
261         n=strlen(in);
262         /* find the last '/', '\' or ':' */
263         for (i=n-1; i>0; i--)
264                 {
265                 if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':'))
266                         {
267                         p= &(in[i+1]);
268                         break;
269                         }
270                 }
271         if (p == NULL)
272                 p=in;
273         n=strlen(p);
274
275 #if defined(OPENSSL_SYS_NETWARE)
276    /* strip off trailing .nlm if present. */
277    if ((n > 4) && (p[n-4] == '.') &&
278       ((p[n-3] == 'n') || (p[n-3] == 'N')) &&
279       ((p[n-2] == 'l') || (p[n-2] == 'L')) &&
280       ((p[n-1] == 'm') || (p[n-1] == 'M')))
281       n-=4;
282 #else
283         /* strip off trailing .exe if present. */
284         if ((n > 4) && (p[n-4] == '.') &&
285                 ((p[n-3] == 'e') || (p[n-3] == 'E')) &&
286                 ((p[n-2] == 'x') || (p[n-2] == 'X')) &&
287                 ((p[n-1] == 'e') || (p[n-1] == 'E')))
288                 n-=4;
289 #endif
290
291         if (n > size-1)
292                 n=size-1;
293
294         for (i=0; i<n; i++)
295                 {
296                 if ((p[i] >= 'A') && (p[i] <= 'Z'))
297                         out[i]=p[i]-'A'+'a';
298                 else
299                         out[i]=p[i];
300                 }
301         out[n]='\0';
302         }
303 #else
304 #ifdef OPENSSL_SYS_VMS
305 void program_name(char *in, char *out, int size)
306         {
307         char *p=in, *q;
308         char *chars=":]>";
309
310         while(*chars != '\0')
311                 {
312                 q=strrchr(p,*chars);
313                 if (q > p)
314                         p = q + 1;
315                 chars++;
316                 }
317
318         q=strrchr(p,'.');
319         if (q == NULL)
320                 q = p + strlen(p);
321         strncpy(out,p,size-1);
322         if (q-p >= size)
323                 {
324                 out[size-1]='\0';
325                 }
326         else
327                 {
328                 out[q-p]='\0';
329                 }
330         }
331 #else
332 void program_name(char *in, char *out, int size)
333         {
334         char *p;
335
336         p=strrchr(in,'/');
337         if (p != NULL)
338                 p++;
339         else
340                 p=in;
341         BUF_strlcpy(out,p,size);
342         }
343 #endif
344 #endif
345
346 int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
347         {
348         int num,len,i;
349         char *p;
350
351         *argc=0;
352         *argv=NULL;
353
354         len=strlen(buf);
355         i=0;
356         if (arg->count == 0)
357                 {
358                 arg->count=20;
359                 arg->data=(char **)OPENSSL_malloc(sizeof(char *)*arg->count);
360                 }
361         for (i=0; i<arg->count; i++)
362                 arg->data[i]=NULL;
363
364         num=0;
365         p=buf;
366         for (;;)
367                 {
368                 /* first scan over white space */
369                 if (!*p) break;
370                 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
371                         p++;
372                 if (!*p) break;
373
374                 /* The start of something good :-) */
375                 if (num >= arg->count)
376                         {
377                         arg->count+=20;
378                         arg->data=(char **)OPENSSL_realloc(arg->data,
379                                 sizeof(char *)*arg->count);
380                         if (argc == 0) return(0);
381                         }
382                 arg->data[num++]=p;
383
384                 /* now look for the end of this */
385                 if ((*p == '\'') || (*p == '\"')) /* scan for closing quote */
386                         {
387                         i= *(p++);
388                         arg->data[num-1]++; /* jump over quote */
389                         while (*p && (*p != i))
390                                 p++;
391                         *p='\0';
392                         }
393                 else
394                         {
395                         while (*p && ((*p != ' ') &&
396                                 (*p != '\t') && (*p != '\n')))
397                                 p++;
398
399                         if (*p == '\0')
400                                 p--;
401                         else
402                                 *p='\0';
403                         }
404                 p++;
405                 }
406         *argc=num;
407         *argv=arg->data;
408         return(1);
409         }
410
411 #ifndef APP_INIT
412 int app_init(long mesgwin)
413         {
414         return(1);
415         }
416 #endif
417
418
419 int dump_cert_text (BIO *out, X509 *x)
420 {
421         char *p;
422
423         p=X509_NAME_oneline(X509_get_subject_name(x),NULL,0);
424         BIO_puts(out,"subject=");
425         BIO_puts(out,p);
426         OPENSSL_free(p);
427
428         p=X509_NAME_oneline(X509_get_issuer_name(x),NULL,0);
429         BIO_puts(out,"\nissuer=");
430         BIO_puts(out,p);
431         BIO_puts(out,"\n");
432         OPENSSL_free(p);
433
434         return 0;
435 }
436
437 static int ui_open(UI *ui)
438         {
439         return UI_method_get_opener(UI_OpenSSL())(ui);
440         }
441 static int ui_read(UI *ui, UI_STRING *uis)
442         {
443         if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
444                 && UI_get0_user_data(ui))
445                 {
446                 switch(UI_get_string_type(uis))
447                         {
448                 case UIT_PROMPT:
449                 case UIT_VERIFY:
450                         {
451                         const char *password =
452                                 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
453                         if (password && password[0] != '\0')
454                                 {
455                                 UI_set_result(ui, uis, password);
456                                 return 1;
457                                 }
458                         }
459                 default:
460                         break;
461                         }
462                 }
463         return UI_method_get_reader(UI_OpenSSL())(ui, uis);
464         }
465 static int ui_write(UI *ui, UI_STRING *uis)
466         {
467         if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
468                 && UI_get0_user_data(ui))
469                 {
470                 switch(UI_get_string_type(uis))
471                         {
472                 case UIT_PROMPT:
473                 case UIT_VERIFY:
474                         {
475                         const char *password =
476                                 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
477                         if (password && password[0] != '\0')
478                                 return 1;
479                         }
480                 default:
481                         break;
482                         }
483                 }
484         return UI_method_get_writer(UI_OpenSSL())(ui, uis);
485         }
486 static int ui_close(UI *ui)
487         {
488         return UI_method_get_closer(UI_OpenSSL())(ui);
489         }
490 int setup_ui_method(void)
491         {
492         ui_method = UI_create_method("OpenSSL application user interface");
493         UI_method_set_opener(ui_method, ui_open);
494         UI_method_set_reader(ui_method, ui_read);
495         UI_method_set_writer(ui_method, ui_write);
496         UI_method_set_closer(ui_method, ui_close);
497         return 0;
498         }
499 void destroy_ui_method(void)
500         {
501         if(ui_method)
502                 {
503                 UI_destroy_method(ui_method);
504                 ui_method = NULL;
505                 }
506         }
507 int password_callback(char *buf, int bufsiz, int verify,
508         PW_CB_DATA *cb_tmp)
509         {
510         UI *ui = NULL;
511         int res = 0;
512         const char *prompt_info = NULL;
513         const char *password = NULL;
514         PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
515
516         if (cb_data)
517                 {
518                 if (cb_data->password)
519                         password = cb_data->password;
520                 if (cb_data->prompt_info)
521                         prompt_info = cb_data->prompt_info;
522                 }
523
524         if (password)
525                 {
526                 res = strlen(password);
527                 if (res > bufsiz)
528                         res = bufsiz;
529                 memcpy(buf, password, res);
530                 return res;
531                 }
532
533         ui = UI_new_method(ui_method);
534         if (ui)
535                 {
536                 int ok = 0;
537                 char *buff = NULL;
538                 int ui_flags = 0;
539                 char *prompt = NULL;
540
541                 prompt = UI_construct_prompt(ui, "pass phrase",
542                         prompt_info);
543
544                 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
545                 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
546
547                 if (ok >= 0)
548                         ok = UI_add_input_string(ui,prompt,ui_flags,buf,
549                                 PW_MIN_LENGTH,BUFSIZ-1);
550                 if (ok >= 0 && verify)
551                         {
552                         buff = (char *)OPENSSL_malloc(bufsiz);
553                         ok = UI_add_verify_string(ui,prompt,ui_flags,buff,
554                                 PW_MIN_LENGTH,BUFSIZ-1, buf);
555                         }
556                 if (ok >= 0)
557                         do
558                                 {
559                                 ok = UI_process(ui);
560                                 }
561                         while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
562
563                 if (buff)
564                         {
565                         OPENSSL_cleanse(buff,(unsigned int)bufsiz);
566                         OPENSSL_free(buff);
567                         }
568
569                 if (ok >= 0)
570                         res = strlen(buf);
571                 if (ok == -1)
572                         {
573                         BIO_printf(bio_err, "User interface error\n");
574                         ERR_print_errors(bio_err);
575                         OPENSSL_cleanse(buf,(unsigned int)bufsiz);
576                         res = 0;
577                         }
578                 if (ok == -2)
579                         {
580                         BIO_printf(bio_err,"aborted!\n");
581                         OPENSSL_cleanse(buf,(unsigned int)bufsiz);
582                         res = 0;
583                         }
584                 UI_free(ui);
585                 OPENSSL_free(prompt);
586                 }
587         return res;
588         }
589
590 static char *app_get_pass(BIO *err, char *arg, int keepbio);
591
592 int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
593 {
594         int same;
595         if(!arg2 || !arg1 || strcmp(arg1, arg2)) same = 0;
596         else same = 1;
597         if(arg1) {
598                 *pass1 = app_get_pass(err, arg1, same);
599                 if(!*pass1) return 0;
600         } else if(pass1) *pass1 = NULL;
601         if(arg2) {
602                 *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
603                 if(!*pass2) return 0;
604         } else if(pass2) *pass2 = NULL;
605         return 1;
606 }
607
608 static char *app_get_pass(BIO *err, char *arg, int keepbio)
609 {
610         char *tmp, tpass[APP_PASS_LEN];
611         static BIO *pwdbio = NULL;
612         int i;
613         if(!strncmp(arg, "pass:", 5)) return BUF_strdup(arg + 5);
614         if(!strncmp(arg, "env:", 4)) {
615                 tmp = getenv(arg + 4);
616                 if(!tmp) {
617                         BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
618                         return NULL;
619                 }
620                 return BUF_strdup(tmp);
621         }
622         if(!keepbio || !pwdbio) {
623                 if(!strncmp(arg, "file:", 5)) {
624                         pwdbio = BIO_new_file(arg + 5, "r");
625                         if(!pwdbio) {
626                                 BIO_printf(err, "Can't open file %s\n", arg + 5);
627                                 return NULL;
628                         }
629                 } else if(!strncmp(arg, "fd:", 3)) {
630                         BIO *btmp;
631                         i = atoi(arg + 3);
632                         if(i >= 0) pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
633                         if((i < 0) || !pwdbio) {
634                                 BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
635                                 return NULL;
636                         }
637                         /* Can't do BIO_gets on an fd BIO so add a buffering BIO */
638                         btmp = BIO_new(BIO_f_buffer());
639                         pwdbio = BIO_push(btmp, pwdbio);
640                 } else if(!strcmp(arg, "stdin")) {
641                         pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
642                         if(!pwdbio) {
643                                 BIO_printf(err, "Can't open BIO for stdin\n");
644                                 return NULL;
645                         }
646                 } else {
647                         BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
648                         return NULL;
649                 }
650         }
651         i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
652         if(keepbio != 1) {
653                 BIO_free_all(pwdbio);
654                 pwdbio = NULL;
655         }
656         if(i <= 0) {
657                 BIO_printf(err, "Error reading password from BIO\n");
658                 return NULL;
659         }
660         tmp = strchr(tpass, '\n');
661         if(tmp) *tmp = 0;
662         return BUF_strdup(tpass);
663 }
664
665 int add_oid_section(BIO *err, CONF *conf)
666 {       
667         char *p;
668         STACK_OF(CONF_VALUE) *sktmp;
669         CONF_VALUE *cnf;
670         int i;
671         if(!(p=NCONF_get_string(conf,NULL,"oid_section")))
672                 {
673                 ERR_clear_error();
674                 return 1;
675                 }
676         if(!(sktmp = NCONF_get_section(conf, p))) {
677                 BIO_printf(err, "problem loading oid section %s\n", p);
678                 return 0;
679         }
680         for(i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
681                 cnf = sk_CONF_VALUE_value(sktmp, i);
682                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
683                         BIO_printf(err, "problem creating object %s=%s\n",
684                                                          cnf->name, cnf->value);
685                         return 0;
686                 }
687         }
688         return 1;
689 }
690
691 static int load_pkcs12(BIO *err, BIO *in, const char *desc,
692                 pem_password_cb *pem_cb,  void *cb_data,
693                 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
694         {
695         const char *pass;
696         char tpass[PEM_BUFSIZE];
697         int len, ret = 0;
698         PKCS12 *p12;
699         p12 = d2i_PKCS12_bio(in, NULL);
700         if (p12 == NULL)
701                 {
702                 BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);    
703                 goto die;
704                 }
705         /* See if an empty password will do */
706         if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
707                 pass = "";
708         else
709                 {
710                 if (!pem_cb)
711                         pem_cb = (pem_password_cb *)password_callback;
712                 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
713                 if (len < 0) 
714                         {
715                         BIO_printf(err, "Passpharse callback error for %s\n",
716                                         desc);
717                         goto die;
718                         }
719                 if (len < PEM_BUFSIZE)
720                         tpass[len] = 0;
721                 if (!PKCS12_verify_mac(p12, tpass, len))
722                         {
723                         BIO_printf(err,
724         "Mac verify error (wrong password?) in PKCS12 file for %s\n", desc);    
725                         goto die;
726                         }
727                 pass = tpass;
728                 }
729         ret = PKCS12_parse(p12, pass, pkey, cert, ca);
730         die:
731         if (p12)
732                 PKCS12_free(p12);
733         return ret;
734         }
735
736 X509 *load_cert(BIO *err, const char *file, int format,
737         const char *pass, ENGINE *e, const char *cert_descrip)
738         {
739         ASN1_HEADER *ah=NULL;
740         BUF_MEM *buf=NULL;
741         X509 *x=NULL;
742         BIO *cert;
743
744         if ((cert=BIO_new(BIO_s_file())) == NULL)
745                 {
746                 ERR_print_errors(err);
747                 goto end;
748                 }
749
750         if (file == NULL)
751                 {
752                 setvbuf(stdin, NULL, _IONBF, 0);
753                 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
754                 }
755         else
756                 {
757                 if (BIO_read_filename(cert,file) <= 0)
758                         {
759                         BIO_printf(err, "Error opening %s %s\n",
760                                 cert_descrip, file);
761                         ERR_print_errors(err);
762                         goto end;
763                         }
764                 }
765
766         if      (format == FORMAT_ASN1)
767                 x=d2i_X509_bio(cert,NULL);
768         else if (format == FORMAT_NETSCAPE)
769                 {
770                 const unsigned char *p,*op;
771                 int size=0,i;
772
773                 /* We sort of have to do it this way because it is sort of nice
774                  * to read the header first and check it, then
775                  * try to read the certificate */
776                 buf=BUF_MEM_new();
777                 for (;;)
778                         {
779                         if ((buf == NULL) || (!BUF_MEM_grow(buf,size+1024*10)))
780                                 goto end;
781                         i=BIO_read(cert,&(buf->data[size]),1024*10);
782                         size+=i;
783                         if (i == 0) break;
784                         if (i < 0)
785                                 {
786                                 perror("reading certificate");
787                                 goto end;
788                                 }
789                         }
790                 p=(unsigned char *)buf->data;
791                 op=p;
792
793                 /* First load the header */
794                 if ((ah=d2i_ASN1_HEADER(NULL,&p,(long)size)) == NULL)
795                         goto end;
796                 if ((ah->header == NULL) || (ah->header->data == NULL) ||
797                         (strncmp(NETSCAPE_CERT_HDR,(char *)ah->header->data,
798                         ah->header->length) != 0))
799                         {
800                         BIO_printf(err,"Error reading header on certificate\n");
801                         goto end;
802                         }
803                 /* header is ok, so now read the object */
804                 p=op;
805                 ah->meth=X509_asn1_meth();
806                 if ((ah=d2i_ASN1_HEADER(&ah,&p,(long)size)) == NULL)
807                         goto end;
808                 x=(X509 *)ah->data;
809                 ah->data=NULL;
810                 }
811         else if (format == FORMAT_PEM)
812                 x=PEM_read_bio_X509_AUX(cert,NULL,
813                         (pem_password_cb *)password_callback, NULL);
814         else if (format == FORMAT_PKCS12)
815                 {
816                 if (!load_pkcs12(err, cert,cert_descrip, NULL, NULL,
817                                         NULL, &x, NULL))
818                         goto end;
819                 }
820         else    {
821                 BIO_printf(err,"bad input format specified for %s\n",
822                         cert_descrip);
823                 goto end;
824                 }
825 end:
826         if (x == NULL)
827                 {
828                 BIO_printf(err,"unable to load certificate\n");
829                 ERR_print_errors(err);
830                 }
831         if (ah != NULL) ASN1_HEADER_free(ah);
832         if (cert != NULL) BIO_free(cert);
833         if (buf != NULL) BUF_MEM_free(buf);
834         return(x);
835         }
836
837 EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
838         const char *pass, ENGINE *e, const char *key_descrip)
839         {
840         BIO *key=NULL;
841         EVP_PKEY *pkey=NULL;
842         PW_CB_DATA cb_data;
843
844         cb_data.password = pass;
845         cb_data.prompt_info = file;
846
847         if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
848                 {
849                 BIO_printf(err,"no keyfile specified\n");
850                 goto end;
851                 }
852 #ifndef OPENSSL_NO_ENGINE
853         if (format == FORMAT_ENGINE)
854                 {
855                 if (!e)
856                         BIO_printf(bio_err,"no engine specified\n");
857                 else
858                         pkey = ENGINE_load_private_key(e, file,
859                                 ui_method, &cb_data);
860                 goto end;
861                 }
862 #endif
863         key=BIO_new(BIO_s_file());
864         if (key == NULL)
865                 {
866                 ERR_print_errors(err);
867                 goto end;
868                 }
869         if (file == NULL && maybe_stdin)
870                 {
871                 setvbuf(stdin, NULL, _IONBF, 0);
872                 BIO_set_fp(key,stdin,BIO_NOCLOSE);
873                 }
874         else
875                 if (BIO_read_filename(key,file) <= 0)
876                         {
877                         BIO_printf(err, "Error opening %s %s\n",
878                                 key_descrip, file);
879                         ERR_print_errors(err);
880                         goto end;
881                         }
882         if (format == FORMAT_ASN1)
883                 {
884                 pkey=d2i_PrivateKey_bio(key, NULL);
885                 }
886         else if (format == FORMAT_PEM)
887                 {
888                 pkey=PEM_read_bio_PrivateKey(key,NULL,
889                         (pem_password_cb *)password_callback, &cb_data);
890                 }
891 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
892         else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
893                 pkey = load_netscape_key(err, key, file, key_descrip, format);
894 #endif
895         else if (format == FORMAT_PKCS12)
896                 {
897                 if (!load_pkcs12(err, key, key_descrip,
898                                 (pem_password_cb *)password_callback, &cb_data,
899                                 &pkey, NULL, NULL))
900                         goto end;
901                 }
902         else
903                 {
904                 BIO_printf(err,"bad input format specified for key file\n");
905                 goto end;
906                 }
907  end:
908         if (key != NULL) BIO_free(key);
909         if (pkey == NULL)
910                 BIO_printf(err,"unable to load %s\n", key_descrip);
911         return(pkey);
912         }
913
914 EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
915         const char *pass, ENGINE *e, const char *key_descrip)
916         {
917         BIO *key=NULL;
918         EVP_PKEY *pkey=NULL;
919         PW_CB_DATA cb_data;
920
921         cb_data.password = pass;
922         cb_data.prompt_info = file;
923
924         if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
925                 {
926                 BIO_printf(err,"no keyfile specified\n");
927                 goto end;
928                 }
929 #ifndef OPENSSL_NO_ENGINE
930         if (format == FORMAT_ENGINE)
931                 {
932                 if (!e)
933                         BIO_printf(bio_err,"no engine specified\n");
934                 else
935                         pkey = ENGINE_load_public_key(e, file,
936                                 ui_method, &cb_data);
937                 goto end;
938                 }
939 #endif
940         key=BIO_new(BIO_s_file());
941         if (key == NULL)
942                 {
943                 ERR_print_errors(err);
944                 goto end;
945                 }
946         if (file == NULL && maybe_stdin)
947                 {
948                 setvbuf(stdin, NULL, _IONBF, 0);
949                 BIO_set_fp(key,stdin,BIO_NOCLOSE);
950                 }
951         else
952                 if (BIO_read_filename(key,file) <= 0)
953                         {
954                         BIO_printf(err, "Error opening %s %s\n",
955                                 key_descrip, file);
956                         ERR_print_errors(err);
957                         goto end;
958                 }
959         if (format == FORMAT_ASN1)
960                 {
961                 pkey=d2i_PUBKEY_bio(key, NULL);
962                 }
963         else if (format == FORMAT_PEM)
964                 {
965                 pkey=PEM_read_bio_PUBKEY(key,NULL,
966                         (pem_password_cb *)password_callback, &cb_data);
967                 }
968 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
969         else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
970                 pkey = load_netscape_key(err, key, file, key_descrip, format);
971 #endif
972         else
973                 {
974                 BIO_printf(err,"bad input format specified for key file\n");
975                 goto end;
976                 }
977  end:
978         if (key != NULL) BIO_free(key);
979         if (pkey == NULL)
980                 BIO_printf(err,"unable to load %s\n", key_descrip);
981         return(pkey);
982         }
983
984 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
985 static EVP_PKEY *
986 load_netscape_key(BIO *err, BIO *key, const char *file,
987                 const char *key_descrip, int format)
988         {
989         EVP_PKEY *pkey;
990         BUF_MEM *buf;
991         RSA     *rsa;
992         const unsigned char *p;
993         int size, i;
994
995         buf=BUF_MEM_new();
996         pkey = EVP_PKEY_new();
997         size = 0;
998         if (buf == NULL || pkey == NULL)
999                 goto error;
1000         for (;;)
1001                 {
1002                 if (!BUF_MEM_grow_clean(buf,size+1024*10))
1003                         goto error;
1004                 i = BIO_read(key, &(buf->data[size]), 1024*10);
1005                 size += i;
1006                 if (i == 0)
1007                         break;
1008                 if (i < 0)
1009                         {
1010                                 BIO_printf(err, "Error reading %s %s",
1011                                         key_descrip, file);
1012                                 goto error;
1013                         }
1014                 }
1015         p=(unsigned char *)buf->data;
1016         rsa = d2i_RSA_NET(NULL,&p,(long)size,NULL,
1017                 (format == FORMAT_IISSGC ? 1 : 0));
1018         if (rsa == NULL)
1019                 goto error;
1020         BUF_MEM_free(buf);
1021         EVP_PKEY_set1_RSA(pkey, rsa);
1022         return pkey;
1023 error:
1024         BUF_MEM_free(buf);
1025         EVP_PKEY_free(pkey);
1026         return NULL;
1027         }
1028 #endif /* ndef OPENSSL_NO_RC4 */
1029
1030 STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
1031         const char *pass, ENGINE *e, const char *cert_descrip)
1032         {
1033         BIO *certs;
1034         int i;
1035         STACK_OF(X509) *othercerts = NULL;
1036         STACK_OF(X509_INFO) *allcerts = NULL;
1037         X509_INFO *xi;
1038         PW_CB_DATA cb_data;
1039
1040         cb_data.password = pass;
1041         cb_data.prompt_info = file;
1042
1043         if((certs = BIO_new(BIO_s_file())) == NULL)
1044                 {
1045                 ERR_print_errors(err);
1046                 goto end;
1047                 }
1048
1049         if (file == NULL)
1050                 BIO_set_fp(certs,stdin,BIO_NOCLOSE);
1051         else
1052                 {
1053                 if (BIO_read_filename(certs,file) <= 0)
1054                         {
1055                         BIO_printf(err, "Error opening %s %s\n",
1056                                 cert_descrip, file);
1057                         ERR_print_errors(err);
1058                         goto end;
1059                         }
1060                 }
1061
1062         if      (format == FORMAT_PEM)
1063                 {
1064                 othercerts = sk_X509_new_null();
1065                 if(!othercerts)
1066                         {
1067                         sk_X509_free(othercerts);
1068                         othercerts = NULL;
1069                         goto end;
1070                         }
1071                 allcerts = PEM_X509_INFO_read_bio(certs, NULL,
1072                                 (pem_password_cb *)password_callback, &cb_data);
1073                 for(i = 0; i < sk_X509_INFO_num(allcerts); i++)
1074                         {
1075                         xi = sk_X509_INFO_value (allcerts, i);
1076                         if (xi->x509)
1077                                 {
1078                                 sk_X509_push(othercerts, xi->x509);
1079                                 xi->x509 = NULL;
1080                                 }
1081                         }
1082                 goto end;
1083                 }
1084         else    {
1085                 BIO_printf(err,"bad input format specified for %s\n",
1086                         cert_descrip);
1087                 goto end;
1088                 }
1089 end:
1090         if (othercerts == NULL)
1091                 {
1092                 BIO_printf(err,"unable to load certificates\n");
1093                 ERR_print_errors(err);
1094                 }
1095         if (allcerts) sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
1096         if (certs != NULL) BIO_free(certs);
1097         return(othercerts);
1098         }
1099
1100
1101 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
1102 /* Return error for unknown extensions */
1103 #define X509V3_EXT_DEFAULT              0
1104 /* Print error for unknown extensions */
1105 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
1106 /* ASN1 parse unknown extensions */
1107 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
1108 /* BIO_dump unknown extensions */
1109 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
1110
1111 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1112                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1113
1114 int set_cert_ex(unsigned long *flags, const char *arg)
1115 {
1116         static const NAME_EX_TBL cert_tbl[] = {
1117                 { "compatible", X509_FLAG_COMPAT, 0xffffffffl},
1118                 { "ca_default", X509_FLAG_CA, 0xffffffffl},
1119                 { "no_header", X509_FLAG_NO_HEADER, 0},
1120                 { "no_version", X509_FLAG_NO_VERSION, 0},
1121                 { "no_serial", X509_FLAG_NO_SERIAL, 0},
1122                 { "no_signame", X509_FLAG_NO_SIGNAME, 0},
1123                 { "no_validity", X509_FLAG_NO_VALIDITY, 0},
1124                 { "no_subject", X509_FLAG_NO_SUBJECT, 0},
1125                 { "no_issuer", X509_FLAG_NO_ISSUER, 0},
1126                 { "no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1127                 { "no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1128                 { "no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1129                 { "no_aux", X509_FLAG_NO_AUX, 0},
1130                 { "no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1131                 { "ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1132                 { "ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1133                 { "ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1134                 { "ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1135                 { NULL, 0, 0}
1136         };
1137         return set_multi_opts(flags, arg, cert_tbl);
1138 }
1139
1140 int set_name_ex(unsigned long *flags, const char *arg)
1141 {
1142         static const NAME_EX_TBL ex_tbl[] = {
1143                 { "esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1144                 { "esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1145                 { "esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1146                 { "use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1147                 { "utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1148                 { "ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1149                 { "show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1150                 { "dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1151                 { "dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1152                 { "dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1153                 { "compat", XN_FLAG_COMPAT, 0xffffffffL},
1154                 { "sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1155                 { "sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1156                 { "sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1157                 { "sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1158                 { "dn_rev", XN_FLAG_DN_REV, 0},
1159                 { "nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1160                 { "sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1161                 { "lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1162                 { "align", XN_FLAG_FN_ALIGN, 0},
1163                 { "oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1164                 { "space_eq", XN_FLAG_SPC_EQ, 0},
1165                 { "dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1166                 { "RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1167                 { "oneline", XN_FLAG_ONELINE, 0xffffffffL},
1168                 { "multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1169                 { "ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1170                 { NULL, 0, 0}
1171         };
1172         return set_multi_opts(flags, arg, ex_tbl);
1173 }
1174
1175 int set_ext_copy(int *copy_type, const char *arg)
1176 {
1177         if (!strcasecmp(arg, "none"))
1178                 *copy_type = EXT_COPY_NONE;
1179         else if (!strcasecmp(arg, "copy"))
1180                 *copy_type = EXT_COPY_ADD;
1181         else if (!strcasecmp(arg, "copyall"))
1182                 *copy_type = EXT_COPY_ALL;
1183         else
1184                 return 0;
1185         return 1;
1186 }
1187
1188 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1189 {
1190         STACK_OF(X509_EXTENSION) *exts = NULL;
1191         X509_EXTENSION *ext, *tmpext;
1192         ASN1_OBJECT *obj;
1193         int i, idx, ret = 0;
1194         if (!x || !req || (copy_type == EXT_COPY_NONE))
1195                 return 1;
1196         exts = X509_REQ_get_extensions(req);
1197
1198         for(i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1199                 ext = sk_X509_EXTENSION_value(exts, i);
1200                 obj = X509_EXTENSION_get_object(ext);
1201                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1202                 /* Does extension exist? */
1203                 if (idx != -1) {
1204                         /* If normal copy don't override existing extension */
1205                         if (copy_type == EXT_COPY_ADD)
1206                                 continue;
1207                         /* Delete all extensions of same type */
1208                         do {
1209                                 tmpext = X509_get_ext(x, idx);
1210                                 X509_delete_ext(x, idx);
1211                                 X509_EXTENSION_free(tmpext);
1212                                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1213                         } while (idx != -1);
1214                 }
1215                 if (!X509_add_ext(x, ext, -1))
1216                         goto end;
1217         }
1218
1219         ret = 1;
1220
1221         end:
1222
1223         sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1224
1225         return ret;
1226 }
1227                 
1228                 
1229                         
1230
1231 static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1232 {
1233         STACK_OF(CONF_VALUE) *vals;
1234         CONF_VALUE *val;
1235         int i, ret = 1;
1236         if(!arg) return 0;
1237         vals = X509V3_parse_list(arg);
1238         for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1239                 val = sk_CONF_VALUE_value(vals, i);
1240                 if (!set_table_opts(flags, val->name, in_tbl))
1241                         ret = 0;
1242         }
1243         sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1244         return ret;
1245 }
1246
1247 static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1248 {
1249         char c;
1250         const NAME_EX_TBL *ptbl;
1251         c = arg[0];
1252
1253         if(c == '-') {
1254                 c = 0;
1255                 arg++;
1256         } else if (c == '+') {
1257                 c = 1;
1258                 arg++;
1259         } else c = 1;
1260
1261         for(ptbl = in_tbl; ptbl->name; ptbl++) {
1262                 if(!strcasecmp(arg, ptbl->name)) {
1263                         *flags &= ~ptbl->mask;
1264                         if(c) *flags |= ptbl->flag;
1265                         else *flags &= ~ptbl->flag;
1266                         return 1;
1267                 }
1268         }
1269         return 0;
1270 }
1271
1272 void print_name(BIO *out, char *title, X509_NAME *nm, unsigned long lflags)
1273 {
1274         char *buf;
1275         char mline = 0;
1276         int indent = 0;
1277
1278         if(title) BIO_puts(out, title);
1279         if((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1280                 mline = 1;
1281                 indent = 4;
1282         }
1283         if(lflags == XN_FLAG_COMPAT) {
1284                 buf = X509_NAME_oneline(nm, 0, 0);
1285                 BIO_puts(out, buf);
1286                 BIO_puts(out, "\n");
1287                 OPENSSL_free(buf);
1288         } else {
1289                 if(mline) BIO_puts(out, "\n");
1290                 X509_NAME_print_ex(out, nm, indent, lflags);
1291                 BIO_puts(out, "\n");
1292         }
1293 }
1294
1295 X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
1296 {
1297         X509_STORE *store;
1298         X509_LOOKUP *lookup;
1299         if(!(store = X509_STORE_new())) goto end;
1300         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
1301         if (lookup == NULL) goto end;
1302         if (CAfile) {
1303                 if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
1304                         BIO_printf(bp, "Error loading file %s\n", CAfile);
1305                         goto end;
1306                 }
1307         } else X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
1308                 
1309         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
1310         if (lookup == NULL) goto end;
1311         if (CApath) {
1312                 if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
1313                         BIO_printf(bp, "Error loading directory %s\n", CApath);
1314                         goto end;
1315                 }
1316         } else X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
1317
1318         ERR_clear_error();
1319         return store;
1320         end:
1321         X509_STORE_free(store);
1322         return NULL;
1323 }
1324
1325 #ifndef OPENSSL_NO_ENGINE
1326 /* Try to load an engine in a shareable library */
1327 static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
1328         {
1329         ENGINE *e = ENGINE_by_id("dynamic");
1330         if (e)
1331                 {
1332                 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1333                         || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
1334                         {
1335                         ENGINE_free(e);
1336                         e = NULL;
1337                         }
1338                 }
1339         return e;
1340         }
1341
1342 ENGINE *setup_engine(BIO *err, const char *engine, int debug)
1343         {
1344         ENGINE *e = NULL;
1345
1346         if (engine)
1347                 {
1348                 if(strcmp(engine, "auto") == 0)
1349                         {
1350                         BIO_printf(err,"enabling auto ENGINE support\n");
1351                         ENGINE_register_all_complete();
1352                         return NULL;
1353                         }
1354                 if((e = ENGINE_by_id(engine)) == NULL
1355                         && (e = try_load_engine(err, engine, debug)) == NULL)
1356                         {
1357                         BIO_printf(err,"invalid engine \"%s\"\n", engine);
1358                         ERR_print_errors(err);
1359                         return NULL;
1360                         }
1361                 if (debug)
1362                         {
1363                         ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM,
1364                                 0, err, 0);
1365                         }
1366                 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1367                 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
1368                         {
1369                         BIO_printf(err,"can't use that engine\n");
1370                         ERR_print_errors(err);
1371                         ENGINE_free(e);
1372                         return NULL;
1373                         }
1374
1375                 BIO_printf(err,"engine \"%s\" set.\n", ENGINE_get_id(e));
1376
1377                 /* Free our "structural" reference. */
1378                 ENGINE_free(e);
1379                 }
1380         return e;
1381         }
1382 #endif
1383
1384 int load_config(BIO *err, CONF *cnf)
1385         {
1386         if (!cnf)
1387                 cnf = config;
1388         if (!cnf)
1389                 return 1;
1390
1391         OPENSSL_load_builtin_modules();
1392
1393         if (CONF_modules_load(cnf, NULL, 0) <= 0)
1394                 {
1395                 BIO_printf(err, "Error configuring OpenSSL\n");
1396                 ERR_print_errors(err);
1397                 return 0;
1398                 }
1399         return 1;
1400         }
1401
1402 char *make_config_name()
1403         {
1404         const char *t=X509_get_default_cert_area();
1405         size_t len;
1406         char *p;
1407
1408         len=strlen(t)+strlen(OPENSSL_CONF)+2;
1409         p=OPENSSL_malloc(len);
1410         BUF_strlcpy(p,t,len);
1411 #ifndef OPENSSL_SYS_VMS
1412         BUF_strlcat(p,"/",len);
1413 #endif
1414         BUF_strlcat(p,OPENSSL_CONF,len);
1415
1416         return p;
1417         }
1418
1419 static unsigned long index_serial_hash(const char **a)
1420         {
1421         const char *n;
1422
1423         n=a[DB_serial];
1424         while (*n == '0') n++;
1425         return(lh_strhash(n));
1426         }
1427
1428 static int index_serial_cmp(const char **a, const char **b)
1429         {
1430         const char *aa,*bb;
1431
1432         for (aa=a[DB_serial]; *aa == '0'; aa++);
1433         for (bb=b[DB_serial]; *bb == '0'; bb++);
1434         return(strcmp(aa,bb));
1435         }
1436
1437 static int index_name_qual(char **a)
1438         { return(a[0][0] == 'V'); }
1439
1440 static unsigned long index_name_hash(const char **a)
1441         { return(lh_strhash(a[DB_name])); }
1442
1443 int index_name_cmp(const char **a, const char **b)
1444         { return(strcmp(a[DB_name],
1445              b[DB_name])); }
1446
1447 static IMPLEMENT_LHASH_HASH_FN(index_serial_hash,const char **)
1448 static IMPLEMENT_LHASH_COMP_FN(index_serial_cmp,const char **)
1449 static IMPLEMENT_LHASH_HASH_FN(index_name_hash,const char **)
1450 static IMPLEMENT_LHASH_COMP_FN(index_name_cmp,const char **)
1451
1452 #undef BSIZE
1453 #define BSIZE 256
1454
1455 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1456         {
1457         BIO *in=NULL;
1458         BIGNUM *ret=NULL;
1459         MS_STATIC char buf[1024];
1460         ASN1_INTEGER *ai=NULL;
1461
1462         ai=ASN1_INTEGER_new();
1463         if (ai == NULL) goto err;
1464
1465         if ((in=BIO_new(BIO_s_file())) == NULL)
1466                 {
1467                 ERR_print_errors(bio_err);
1468                 goto err;
1469                 }
1470
1471         if (BIO_read_filename(in,serialfile) <= 0)
1472                 {
1473                 if (!create)
1474                         {
1475                         perror(serialfile);
1476                         goto err;
1477                         }
1478                 else
1479                         {
1480                         ret=BN_new();
1481                         if (ret == NULL || !rand_serial(ret, ai))
1482                                 BIO_printf(bio_err, "Out of memory\n");
1483                         }
1484                 }
1485         else
1486                 {
1487                 if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1488                         {
1489                         BIO_printf(bio_err,"unable to load number from %s\n",
1490                                 serialfile);
1491                         goto err;
1492                         }
1493                 ret=ASN1_INTEGER_to_BN(ai,NULL);
1494                 if (ret == NULL)
1495                         {
1496                         BIO_printf(bio_err,"error converting number from bin to BIGNUM\n");
1497                         goto err;
1498                         }
1499                 }
1500
1501         if (ret && retai)
1502                 {
1503                 *retai = ai;
1504                 ai = NULL;
1505                 }
1506  err:
1507         if (in != NULL) BIO_free(in);
1508         if (ai != NULL) ASN1_INTEGER_free(ai);
1509         return(ret);
1510         }
1511
1512 int save_serial(char *serialfile, char *suffix, BIGNUM *serial, ASN1_INTEGER **retai)
1513         {
1514         char buf[1][BSIZE];
1515         BIO *out = NULL;
1516         int ret=0;
1517         ASN1_INTEGER *ai=NULL;
1518         int j;
1519
1520         if (suffix == NULL)
1521                 j = strlen(serialfile);
1522         else
1523                 j = strlen(serialfile) + strlen(suffix) + 1;
1524         if (j >= BSIZE)
1525                 {
1526                 BIO_printf(bio_err,"file name too long\n");
1527                 goto err;
1528                 }
1529
1530         if (suffix == NULL)
1531                 BUF_strlcpy(buf[0], serialfile, BSIZE);
1532         else
1533                 {
1534 #ifndef OPENSSL_SYS_VMS
1535                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1536 #else
1537                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1538 #endif
1539                 }
1540 #ifdef RL_DEBUG
1541         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1542 #endif
1543         out=BIO_new(BIO_s_file());
1544         if (out == NULL)
1545                 {
1546                 ERR_print_errors(bio_err);
1547                 goto err;
1548                 }
1549         if (BIO_write_filename(out,buf[0]) <= 0)
1550                 {
1551                 perror(serialfile);
1552                 goto err;
1553                 }
1554
1555         if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1556                 {
1557                 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1558                 goto err;
1559                 }
1560         i2a_ASN1_INTEGER(out,ai);
1561         BIO_puts(out,"\n");
1562         ret=1;
1563         if (retai)
1564                 {
1565                 *retai = ai;
1566                 ai = NULL;
1567                 }
1568 err:
1569         if (out != NULL) BIO_free_all(out);
1570         if (ai != NULL) ASN1_INTEGER_free(ai);
1571         return(ret);
1572         }
1573
1574 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1575         {
1576         char buf[5][BSIZE];
1577         int i,j;
1578         struct stat sb;
1579
1580         i = strlen(serialfile) + strlen(old_suffix);
1581         j = strlen(serialfile) + strlen(new_suffix);
1582         if (i > j) j = i;
1583         if (j + 1 >= BSIZE)
1584                 {
1585                 BIO_printf(bio_err,"file name too long\n");
1586                 goto err;
1587                 }
1588
1589 #ifndef OPENSSL_SYS_VMS
1590         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1591                 serialfile, new_suffix);
1592 #else
1593         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1594                 serialfile, new_suffix);
1595 #endif
1596 #ifndef OPENSSL_SYS_VMS
1597         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1598                 serialfile, old_suffix);
1599 #else
1600         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1601                 serialfile, old_suffix);
1602 #endif
1603         if (stat(serialfile,&sb) < 0)
1604                 {
1605                 if (errno != ENOENT 
1606 #ifdef ENOTDIR
1607                         && errno != ENOTDIR)
1608 #endif
1609                         goto err;
1610                 }
1611         else
1612                 {
1613 #ifdef RL_DEBUG
1614                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1615                         serialfile, buf[1]);
1616 #endif
1617                 if (rename(serialfile,buf[1]) < 0)
1618                         {
1619                         BIO_printf(bio_err,
1620                                 "unable to rename %s to %s\n",
1621                                 serialfile, buf[1]);
1622                         perror("reason");
1623                         goto err;
1624                         }
1625                 }
1626 #ifdef RL_DEBUG
1627         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1628                 buf[0],serialfile);
1629 #endif
1630         if (rename(buf[0],serialfile) < 0)
1631                 {
1632                 BIO_printf(bio_err,
1633                         "unable to rename %s to %s\n",
1634                         buf[0],serialfile);
1635                 perror("reason");
1636                 rename(buf[1],serialfile);
1637                 goto err;
1638                 }
1639         return 1;
1640  err:
1641         return 0;
1642         }
1643
1644 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1645         {
1646         BIGNUM *btmp;
1647         int ret = 0;
1648         if (b)
1649                 btmp = b;
1650         else
1651                 btmp = BN_new();
1652
1653         if (!btmp)
1654                 return 0;
1655
1656         if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1657                 goto error;
1658         if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1659                 goto error;
1660
1661         ret = 1;
1662         
1663         error:
1664
1665         if (!b)
1666                 BN_free(btmp);
1667         
1668         return ret;
1669         }
1670
1671 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1672         {
1673         CA_DB *retdb = NULL;
1674         TXT_DB *tmpdb = NULL;
1675         BIO *in = BIO_new(BIO_s_file());
1676         CONF *dbattr_conf = NULL;
1677         char buf[1][BSIZE];
1678         long errorline= -1;
1679
1680         if (in == NULL)
1681                 {
1682                 ERR_print_errors(bio_err);
1683                 goto err;
1684                 }
1685         if (BIO_read_filename(in,dbfile) <= 0)
1686                 {
1687                 perror(dbfile);
1688                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
1689                 goto err;
1690                 }
1691         if ((tmpdb = TXT_DB_read(in,DB_NUMBER)) == NULL)
1692                 {
1693                 if (tmpdb != NULL) TXT_DB_free(tmpdb);
1694                 goto err;
1695                 }
1696
1697 #ifndef OPENSSL_SYS_VMS
1698         BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1699 #else
1700         BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1701 #endif
1702         dbattr_conf = NCONF_new(NULL);
1703         if (NCONF_load(dbattr_conf,buf[0],&errorline) <= 0)
1704                 {
1705                 if (errorline > 0)
1706                         {
1707                         BIO_printf(bio_err,
1708                                 "error on line %ld of db attribute file '%s'\n"
1709                                 ,errorline,buf[0]);
1710                         goto err;
1711                         }
1712                 else
1713                         {
1714                         NCONF_free(dbattr_conf);
1715                         dbattr_conf = NULL;
1716                         }
1717                 }
1718
1719         if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL)
1720                 {
1721                 fprintf(stderr, "Out of memory\n");
1722                 goto err;
1723                 }
1724
1725         retdb->db = tmpdb;
1726         tmpdb = NULL;
1727         if (db_attr)
1728                 retdb->attributes = *db_attr;
1729         else
1730                 {
1731                 retdb->attributes.unique_subject = 1;
1732                 }
1733
1734         if (dbattr_conf)
1735                 {
1736                 char *p = NCONF_get_string(dbattr_conf,NULL,"unique_subject");
1737                 if (p)
1738                         {
1739 #ifdef RL_DEBUG
1740                         BIO_printf(bio_err, "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1741 #endif
1742                         retdb->attributes.unique_subject = parse_yesno(p,1);
1743                         }
1744                 }
1745
1746  err:
1747         if (dbattr_conf) NCONF_free(dbattr_conf);
1748         if (tmpdb) TXT_DB_free(tmpdb);
1749         if (in) BIO_free_all(in);
1750         return retdb;
1751         }
1752
1753 int index_index(CA_DB *db)
1754         {
1755         if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1756                                 LHASH_HASH_FN(index_serial_hash),
1757                                 LHASH_COMP_FN(index_serial_cmp)))
1758                 {
1759                 BIO_printf(bio_err,
1760                   "error creating serial number index:(%ld,%ld,%ld)\n",
1761                                         db->db->error,db->db->arg1,db->db->arg2);
1762                         return 0;
1763                 }
1764
1765         if (db->attributes.unique_subject
1766                 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1767                         LHASH_HASH_FN(index_name_hash),
1768                         LHASH_COMP_FN(index_name_cmp)))
1769                 {
1770                 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
1771                         db->db->error,db->db->arg1,db->db->arg2);
1772                 return 0;
1773                 }
1774         return 1;
1775         }
1776
1777 int save_index(char *dbfile, char *suffix, CA_DB *db)
1778         {
1779         char buf[3][BSIZE];
1780         BIO *out = BIO_new(BIO_s_file());
1781         int j;
1782
1783         if (out == NULL)
1784                 {
1785                 ERR_print_errors(bio_err);
1786                 goto err;
1787                 }
1788
1789         j = strlen(dbfile) + strlen(suffix);
1790         if (j + 6 >= BSIZE)
1791                 {
1792                 BIO_printf(bio_err,"file name too long\n");
1793                 goto err;
1794                 }
1795
1796 #ifndef OPENSSL_SYS_VMS
1797         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1798 #else
1799         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1800 #endif
1801 #ifndef OPENSSL_SYS_VMS
1802         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1803 #else
1804         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1805 #endif
1806 #ifndef OPENSSL_SYS_VMS
1807         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1808 #else
1809         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1810 #endif
1811 #ifdef RL_DEBUG
1812         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1813 #endif
1814         if (BIO_write_filename(out,buf[0]) <= 0)
1815                 {
1816                 perror(dbfile);
1817                 BIO_printf(bio_err,"unable to open '%s'\n", dbfile);
1818                 goto err;
1819                 }
1820         j=TXT_DB_write(out,db->db);
1821         if (j <= 0) goto err;
1822                         
1823         BIO_free(out);
1824
1825         out = BIO_new(BIO_s_file());
1826 #ifdef RL_DEBUG
1827         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1828 #endif
1829         if (BIO_write_filename(out,buf[1]) <= 0)
1830                 {
1831                 perror(buf[2]);
1832                 BIO_printf(bio_err,"unable to open '%s'\n", buf[2]);
1833                 goto err;
1834                 }
1835         BIO_printf(out,"unique_subject = %s\n",
1836                 db->attributes.unique_subject ? "yes" : "no");
1837         BIO_free(out);
1838
1839         return 1;
1840  err:
1841         return 0;
1842         }
1843
1844 int rotate_index(char *dbfile, char *new_suffix, char *old_suffix)
1845         {
1846         char buf[5][BSIZE];
1847         int i,j;
1848         struct stat sb;
1849
1850         i = strlen(dbfile) + strlen(old_suffix);
1851         j = strlen(dbfile) + strlen(new_suffix);
1852         if (i > j) j = i;
1853         if (j + 6 >= BSIZE)
1854                 {
1855                 BIO_printf(bio_err,"file name too long\n");
1856                 goto err;
1857                 }
1858
1859 #ifndef OPENSSL_SYS_VMS
1860         j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1861 #else
1862         j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1863 #endif
1864 #ifndef OPENSSL_SYS_VMS
1865         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s",
1866                 dbfile, new_suffix);
1867 #else
1868         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s",
1869                 dbfile, new_suffix);
1870 #endif
1871 #ifndef OPENSSL_SYS_VMS
1872         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1873                 dbfile, new_suffix);
1874 #else
1875         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1876                 dbfile, new_suffix);
1877 #endif
1878 #ifndef OPENSSL_SYS_VMS
1879         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1880                 dbfile, old_suffix);
1881 #else
1882         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1883                 dbfile, old_suffix);
1884 #endif
1885 #ifndef OPENSSL_SYS_VMS
1886         j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s",
1887                 dbfile, old_suffix);
1888 #else
1889         j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s",
1890                 dbfile, old_suffix);
1891 #endif
1892         if (stat(dbfile,&sb) < 0)
1893                 {
1894                 if (errno != ENOENT 
1895 #ifdef ENOTDIR
1896                         && errno != ENOTDIR)
1897 #endif
1898                         goto err;
1899                 }
1900         else
1901                 {
1902 #ifdef RL_DEBUG
1903                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1904                         dbfile, buf[1]);
1905 #endif
1906                 if (rename(dbfile,buf[1]) < 0)
1907                         {
1908                         BIO_printf(bio_err,
1909                                 "unable to rename %s to %s\n",
1910                                 dbfile, buf[1]);
1911                         perror("reason");
1912                         goto err;
1913                         }
1914                 }
1915 #ifdef RL_DEBUG
1916         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1917                 buf[0],dbfile);
1918 #endif
1919         if (rename(buf[0],dbfile) < 0)
1920                 {
1921                 BIO_printf(bio_err,
1922                         "unable to rename %s to %s\n",
1923                         buf[0],dbfile);
1924                 perror("reason");
1925                 rename(buf[1],dbfile);
1926                 goto err;
1927                 }
1928         if (stat(buf[4],&sb) < 0)
1929                 {
1930                 if (errno != ENOENT 
1931 #ifdef ENOTDIR
1932                         && errno != ENOTDIR)
1933 #endif
1934                         goto err;
1935                 }
1936         else
1937                 {
1938 #ifdef RL_DEBUG
1939                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1940                         buf[4],buf[3]);
1941 #endif
1942                 if (rename(buf[4],buf[3]) < 0)
1943                         {
1944                         BIO_printf(bio_err,
1945                                 "unable to rename %s to %s\n",
1946                                 buf[4], buf[3]);
1947                         perror("reason");
1948                         rename(dbfile,buf[0]);
1949                         rename(buf[1],dbfile);
1950                         goto err;
1951                         }
1952                 }
1953 #ifdef RL_DEBUG
1954         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1955                 buf[2],buf[4]);
1956 #endif
1957         if (rename(buf[2],buf[4]) < 0)
1958                 {
1959                 BIO_printf(bio_err,
1960                         "unable to rename %s to %s\n",
1961                         buf[2],buf[4]);
1962                 perror("reason");
1963                 rename(buf[3],buf[4]);
1964                 rename(dbfile,buf[0]);
1965                 rename(buf[1],dbfile);
1966                 goto err;
1967                 }
1968         return 1;
1969  err:
1970         return 0;
1971         }
1972
1973 void free_index(CA_DB *db)
1974         {
1975         if (db)
1976                 {
1977                 if (db->db) TXT_DB_free(db->db);
1978                 OPENSSL_free(db);
1979                 }
1980         }
1981
1982 int parse_yesno(char *str, int def)
1983         {
1984         int ret = def;
1985         if (str)
1986                 {
1987                 switch (*str)
1988                         {
1989                 case 'f': /* false */
1990                 case 'F': /* FALSE */
1991                 case 'n': /* no */
1992                 case 'N': /* NO */
1993                 case '0': /* 0 */
1994                         ret = 0;
1995                         break;
1996                 case 't': /* true */
1997                 case 'T': /* TRUE */
1998                 case 'y': /* yes */
1999                 case 'Y': /* YES */
2000                 case '1': /* 1 */
2001                         ret = 0;
2002                         break;
2003                 default:
2004                         ret = def;
2005                         break;
2006                         }
2007                 }
2008         return ret;
2009         }
2010
2011 /*
2012  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
2013  * where characters may be escaped by \
2014  */
2015 X509_NAME *parse_name(char *subject, long chtype, int multirdn)
2016         {
2017         size_t buflen = strlen(subject)+1; /* to copy the types and values into. due to escaping, the copy can only become shorter */
2018         char *buf = OPENSSL_malloc(buflen);
2019         size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
2020         char **ne_types = OPENSSL_malloc(max_ne * sizeof (char *));
2021         char **ne_values = OPENSSL_malloc(max_ne * sizeof (char *));
2022         int *mval = OPENSSL_malloc (max_ne * sizeof (int));
2023
2024         char *sp = subject, *bp = buf;
2025         int i, ne_num = 0;
2026
2027         X509_NAME *n = NULL;
2028         int nid;
2029
2030         if (!buf || !ne_types || !ne_values)
2031                 {
2032                 BIO_printf(bio_err, "malloc error\n");
2033                 goto error;
2034                 }       
2035
2036         if (*subject != '/')
2037                 {
2038                 BIO_printf(bio_err, "Subject does not start with '/'.\n");
2039                 goto error;
2040                 }
2041         sp++; /* skip leading / */
2042
2043         /* no multivalued RDN by default */
2044         mval[ne_num] = 0;
2045
2046         while (*sp)
2047                 {
2048                 /* collect type */
2049                 ne_types[ne_num] = bp;
2050                 while (*sp)
2051                         {
2052                         if (*sp == '\\') /* is there anything to escape in the type...? */
2053                                 {
2054                                 if (*++sp)
2055                                         *bp++ = *sp++;
2056                                 else    
2057                                         {
2058                                         BIO_printf(bio_err, "escape character at end of string\n");
2059                                         goto error;
2060                                         }
2061                                 }       
2062                         else if (*sp == '=')
2063                                 {
2064                                 sp++;
2065                                 *bp++ = '\0';
2066                                 break;
2067                                 }
2068                         else
2069                                 *bp++ = *sp++;
2070                         }
2071                 if (!*sp)
2072                         {
2073                         BIO_printf(bio_err, "end of string encountered while processing type of subject name element #%d\n", ne_num);
2074                         goto error;
2075                         }
2076                 ne_values[ne_num] = bp;
2077                 while (*sp)
2078                         {
2079                         if (*sp == '\\')
2080                                 {
2081                                 if (*++sp)
2082                                         *bp++ = *sp++;
2083                                 else
2084                                         {
2085                                         BIO_printf(bio_err, "escape character at end of string\n");
2086                                         goto error;
2087                                         }
2088                                 }
2089                         else if (*sp == '/')
2090                                 {
2091                                 sp++;
2092                                 /* no multivalued RDN by default */
2093                                 mval[ne_num+1] = 0;
2094                                 break;
2095                                 }
2096                         else if (*sp == '+' && multirdn)
2097                                 {
2098                                 /* a not escaped + signals a mutlivalued RDN */
2099                                 sp++;
2100                                 mval[ne_num+1] = -1;
2101                                 break;
2102                                 }
2103                         else
2104                                 *bp++ = *sp++;
2105                         }
2106                 *bp++ = '\0';
2107                 ne_num++;
2108                 }       
2109
2110         if (!(n = X509_NAME_new()))
2111                 goto error;
2112
2113         for (i = 0; i < ne_num; i++)
2114                 {
2115                 if ((nid=OBJ_txt2nid(ne_types[i])) == NID_undef)
2116                         {
2117                         BIO_printf(bio_err, "Subject Attribute %s has no known NID, skipped\n", ne_types[i]);
2118                         continue;
2119                         }
2120
2121                 if (!*ne_values[i])
2122                         {
2123                         BIO_printf(bio_err, "No value provided for Subject Attribute %s, skipped\n", ne_types[i]);
2124                         continue;
2125                         }
2126
2127                 if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char*)ne_values[i], -1,-1,mval[i]))
2128                         goto error;
2129                 }
2130
2131         OPENSSL_free(ne_values);
2132         OPENSSL_free(ne_types);
2133         OPENSSL_free(buf);
2134         return n;
2135
2136 error:
2137         X509_NAME_free(n);
2138         if (ne_values)
2139                 OPENSSL_free(ne_values);
2140         if (ne_types)
2141                 OPENSSL_free(ne_types);
2142         if (buf)
2143                 OPENSSL_free(buf);
2144         return NULL;
2145 }
2146
2147 /* This code MUST COME AFTER anything that uses rename() */
2148 #ifdef OPENSSL_SYS_WIN32
2149 int WIN32_rename(char *from, char *to)
2150         {
2151 #ifndef OPENSSL_SYS_WINCE
2152         /* Windows rename gives an error if 'to' exists, so delete it
2153          * first and ignore file not found errror
2154          */
2155         if((remove(to) != 0) && (errno != ENOENT))
2156                 return -1;
2157 #undef rename
2158         return rename(from, to);
2159 #else
2160         /* convert strings to UNICODE */
2161         {
2162         BOOL result = FALSE;
2163         WCHAR* wfrom;
2164         WCHAR* wto;
2165         int i;
2166         wfrom = malloc((strlen(from)+1)*2);
2167         wto = malloc((strlen(to)+1)*2);
2168         if (wfrom != NULL && wto != NULL)
2169                 {
2170                 for (i=0; i<(int)strlen(from)+1; i++)
2171                         wfrom[i] = (short)from[i];
2172                 for (i=0; i<(int)strlen(to)+1; i++)
2173                         wto[i] = (short)to[i];
2174                 result = MoveFile(wfrom, wto);
2175                 }
2176         if (wfrom != NULL)
2177                 free(wfrom);
2178         if (wto != NULL)
2179                 free(wto);
2180         return result;
2181         }
2182 #endif
2183         }
2184 #endif
2185
2186 int args_verify(char ***pargs, int *pargc,
2187                         int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
2188         {
2189         ASN1_OBJECT *otmp = NULL;
2190         unsigned long flags = 0;
2191         int i;
2192         int purpose = 0;
2193         char **oldargs = *pargs;
2194         char *arg = **pargs, *argn = (*pargs)[1];
2195         if (!strcmp(arg, "-policy"))
2196                 {
2197                 if (!argn)
2198                         *badarg = 1;
2199                 else
2200                         {
2201                         otmp = OBJ_txt2obj(argn, 0);
2202                         if (!otmp)
2203                                 {
2204                                 BIO_printf(err, "Invalid Policy \"%s\"\n",
2205                                                                         argn);
2206                                 *badarg = 1;
2207                                 }
2208                         }
2209                 (*pargs)++;
2210                 }
2211         else if (strcmp(arg,"-purpose") == 0)
2212                 {
2213                 X509_PURPOSE *xptmp;
2214                 if (!argn)
2215                         *badarg = 1;
2216                 else
2217                         {
2218                         i = X509_PURPOSE_get_by_sname(argn);
2219                         if(i < 0)
2220                                 {
2221                                 BIO_printf(err, "unrecognized purpose\n");
2222                                 *badarg = 1;
2223                                 }
2224                         else
2225                                 {
2226                                 xptmp = X509_PURPOSE_get0(i);
2227                                 purpose = X509_PURPOSE_get_id(xptmp);
2228                                 }
2229                         }
2230                 (*pargs)++;
2231                 }
2232         else if (!strcmp(arg, "-ignore_critical"))
2233                 flags |= X509_V_FLAG_IGNORE_CRITICAL;
2234         else if (!strcmp(arg, "-issuer_checks"))
2235                 flags |= X509_V_FLAG_CB_ISSUER_CHECK;
2236         else if (!strcmp(arg, "-crl_check"))
2237                 flags |=  X509_V_FLAG_CRL_CHECK;
2238         else if (!strcmp(arg, "-crl_check_all"))
2239                 flags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
2240         else if (!strcmp(arg, "-policy_check"))
2241                 flags |= X509_V_FLAG_POLICY_CHECK;
2242         else if (!strcmp(arg, "-explicit_policy"))
2243                 flags |= X509_V_FLAG_EXPLICIT_POLICY;
2244         else if (!strcmp(arg, "-x509_strict"))
2245                 flags |= X509_V_FLAG_X509_STRICT;
2246         else if (!strcmp(arg, "-policy_print"))
2247                 flags |= X509_V_FLAG_NOTIFY_POLICY;
2248         else
2249                 return 0;
2250
2251         if (*badarg)
2252                 {
2253                 if (*pm)
2254                         X509_VERIFY_PARAM_free(*pm);
2255                 *pm = NULL;
2256                 goto end;
2257                 }
2258
2259         if (!*pm && !(*pm = X509_VERIFY_PARAM_new()))
2260                 {
2261                 *badarg = 1;
2262                 goto end;
2263                 }
2264
2265         if (otmp)
2266                 X509_VERIFY_PARAM_add0_policy(*pm, otmp);
2267         if (flags)
2268                 X509_VERIFY_PARAM_set_flags(*pm, flags);
2269
2270         if (purpose)
2271                 X509_VERIFY_PARAM_set_purpose(*pm, purpose);
2272
2273         end:
2274
2275         (*pargs)++;
2276
2277         if (pargc)
2278                 *pargc -= *pargs - oldargs;
2279
2280         return 1;
2281
2282         }
2283
2284 static void nodes_print(BIO *out, char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2285         {
2286         X509_POLICY_NODE *node;
2287         int i;
2288         BIO_printf(out, "%s Policies:", name);
2289         if (nodes)
2290                 {
2291                 BIO_puts(out, "\n");
2292                 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++)
2293                         {
2294                         node = sk_X509_POLICY_NODE_value(nodes, i);
2295                         X509_POLICY_NODE_print(out, node, 2);
2296                         }
2297                 }
2298         else
2299                 BIO_puts(out, " <empty>\n");
2300         }
2301
2302 void policies_print(BIO *out, X509_STORE_CTX *ctx)
2303         {
2304         X509_POLICY_TREE *tree;
2305         int explicit_policy;
2306         int free_out = 0;
2307         if (out == NULL)
2308                 {
2309                 out = BIO_new_fp(stderr, BIO_NOCLOSE);
2310                 free_out = 1;
2311                 }
2312         tree = X509_STORE_CTX_get0_policy_tree(ctx);
2313         explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2314
2315         BIO_printf(out, "Require explicit Policy: %s\n",
2316                                 explicit_policy ? "True" : "False");
2317
2318         nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
2319         nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
2320         if (free_out)
2321                 BIO_free(out);
2322         }