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