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