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