Allow RSA key-generation to specify an arbitrary public exponent. Jelte
[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                         ret=BN_new();
1438                         if (ret == NULL || !rand_serial(ret, ai))
1439                                 BIO_printf(bio_err, "Out of memory\n");
1440                         }
1441                 }
1442         else
1443                 {
1444                 if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1445                         {
1446                         BIO_printf(bio_err,"unable to load number from %s\n",
1447                                 serialfile);
1448                         goto err;
1449                         }
1450                 ret=ASN1_INTEGER_to_BN(ai,NULL);
1451                 if (ret == NULL)
1452                         {
1453                         BIO_printf(bio_err,"error converting number from bin to BIGNUM\n");
1454                         goto err;
1455                         }
1456                 }
1457
1458         if (ret && retai)
1459                 {
1460                 *retai = ai;
1461                 ai = NULL;
1462                 }
1463  err:
1464         if (in != NULL) BIO_free(in);
1465         if (ai != NULL) ASN1_INTEGER_free(ai);
1466         return(ret);
1467         }
1468
1469 int save_serial(char *serialfile, char *suffix, BIGNUM *serial, ASN1_INTEGER **retai)
1470         {
1471         char buf[1][BSIZE];
1472         BIO *out = NULL;
1473         int ret=0;
1474         ASN1_INTEGER *ai=NULL;
1475         int j;
1476
1477         if (suffix == NULL)
1478                 j = strlen(serialfile);
1479         else
1480                 j = strlen(serialfile) + strlen(suffix) + 1;
1481         if (j >= BSIZE)
1482                 {
1483                 BIO_printf(bio_err,"file name too long\n");
1484                 goto err;
1485                 }
1486
1487         if (suffix == NULL)
1488                 BUF_strlcpy(buf[0], serialfile, BSIZE);
1489         else
1490                 {
1491 #ifndef OPENSSL_SYS_VMS
1492                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1493 #else
1494                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1495 #endif
1496                 }
1497 #ifdef RL_DEBUG
1498         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1499 #endif
1500         out=BIO_new(BIO_s_file());
1501         if (out == NULL)
1502                 {
1503                 ERR_print_errors(bio_err);
1504                 goto err;
1505                 }
1506         if (BIO_write_filename(out,buf[0]) <= 0)
1507                 {
1508                 perror(serialfile);
1509                 goto err;
1510                 }
1511
1512         if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1513                 {
1514                 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1515                 goto err;
1516                 }
1517         i2a_ASN1_INTEGER(out,ai);
1518         BIO_puts(out,"\n");
1519         ret=1;
1520         if (retai)
1521                 {
1522                 *retai = ai;
1523                 ai = NULL;
1524                 }
1525 err:
1526         if (out != NULL) BIO_free_all(out);
1527         if (ai != NULL) ASN1_INTEGER_free(ai);
1528         return(ret);
1529         }
1530
1531 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1532         {
1533         char buf[5][BSIZE];
1534         int i,j;
1535         struct stat sb;
1536
1537         i = strlen(serialfile) + strlen(old_suffix);
1538         j = strlen(serialfile) + strlen(new_suffix);
1539         if (i > j) j = i;
1540         if (j + 1 >= BSIZE)
1541                 {
1542                 BIO_printf(bio_err,"file name too long\n");
1543                 goto err;
1544                 }
1545
1546 #ifndef OPENSSL_SYS_VMS
1547         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1548                 serialfile, new_suffix);
1549 #else
1550         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1551                 serialfile, new_suffix);
1552 #endif
1553 #ifndef OPENSSL_SYS_VMS
1554         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1555                 serialfile, old_suffix);
1556 #else
1557         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1558                 serialfile, old_suffix);
1559 #endif
1560         if (stat(serialfile,&sb) < 0)
1561                 {
1562                 if (errno != ENOENT 
1563 #ifdef ENOTDIR
1564                         && errno != ENOTDIR)
1565 #endif
1566                         goto err;
1567                 }
1568         else
1569                 {
1570 #ifdef RL_DEBUG
1571                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1572                         serialfile, buf[1]);
1573 #endif
1574                 if (rename(serialfile,buf[1]) < 0)
1575                         {
1576                         BIO_printf(bio_err,
1577                                 "unable to rename %s to %s\n",
1578                                 serialfile, buf[1]);
1579                         perror("reason");
1580                         goto err;
1581                         }
1582                 }
1583 #ifdef RL_DEBUG
1584         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1585                 buf[0],serialfile);
1586 #endif
1587         if (rename(buf[0],serialfile) < 0)
1588                 {
1589                 BIO_printf(bio_err,
1590                         "unable to rename %s to %s\n",
1591                         buf[0],serialfile);
1592                 perror("reason");
1593                 rename(buf[1],serialfile);
1594                 goto err;
1595                 }
1596         return 1;
1597  err:
1598         return 0;
1599         }
1600
1601 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1602         {
1603         BIGNUM *btmp;
1604         int ret = 0;
1605         if (b)
1606                 btmp = b;
1607         else
1608                 btmp = BN_new();
1609
1610         if (!btmp)
1611                 return 0;
1612
1613         if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1614                 goto error;
1615         if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1616                 goto error;
1617
1618         ret = 1;
1619         
1620         error:
1621
1622         if (!b)
1623                 BN_free(btmp);
1624         
1625         return ret;
1626         }
1627
1628 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1629         {
1630         CA_DB *retdb = NULL;
1631         TXT_DB *tmpdb = NULL;
1632         BIO *in = BIO_new(BIO_s_file());
1633         CONF *dbattr_conf = NULL;
1634         char buf[1][BSIZE];
1635         long errorline= -1;
1636
1637         if (in == NULL)
1638                 {
1639                 ERR_print_errors(bio_err);
1640                 goto err;
1641                 }
1642         if (BIO_read_filename(in,dbfile) <= 0)
1643                 {
1644                 perror(dbfile);
1645                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
1646                 goto err;
1647                 }
1648         if ((tmpdb = TXT_DB_read(in,DB_NUMBER)) == NULL)
1649                 {
1650                 if (tmpdb != NULL) TXT_DB_free(tmpdb);
1651                 goto err;
1652                 }
1653
1654 #ifndef OPENSSL_SYS_VMS
1655         BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1656 #else
1657         BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1658 #endif
1659         dbattr_conf = NCONF_new(NULL);
1660         if (NCONF_load(dbattr_conf,buf[0],&errorline) <= 0)
1661                 {
1662                 if (errorline > 0)
1663                         {
1664                         BIO_printf(bio_err,
1665                                 "error on line %ld of db attribute file '%s'\n"
1666                                 ,errorline,buf[0]);
1667                         goto err;
1668                         }
1669                 else
1670                         {
1671                         NCONF_free(dbattr_conf);
1672                         dbattr_conf = NULL;
1673                         }
1674                 }
1675
1676         if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL)
1677                 {
1678                 fprintf(stderr, "Out of memory\n");
1679                 goto err;
1680                 }
1681
1682         retdb->db = tmpdb;
1683         tmpdb = NULL;
1684         if (db_attr)
1685                 retdb->attributes = *db_attr;
1686         else
1687                 {
1688                 retdb->attributes.unique_subject = 1;
1689                 }
1690
1691         if (dbattr_conf)
1692                 {
1693                 char *p = NCONF_get_string(dbattr_conf,NULL,"unique_subject");
1694                 if (p)
1695                         {
1696 #ifdef RL_DEBUG
1697                         BIO_printf(bio_err, "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1698 #endif
1699                         retdb->attributes.unique_subject = parse_yesno(p,1);
1700                         }
1701                 }
1702
1703  err:
1704         if (dbattr_conf) NCONF_free(dbattr_conf);
1705         if (tmpdb) TXT_DB_free(tmpdb);
1706         if (in) BIO_free_all(in);
1707         return retdb;
1708         }
1709
1710 int index_index(CA_DB *db)
1711         {
1712         if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1713                                 LHASH_HASH_FN(index_serial_hash),
1714                                 LHASH_COMP_FN(index_serial_cmp)))
1715                 {
1716                 BIO_printf(bio_err,
1717                   "error creating serial number index:(%ld,%ld,%ld)\n",
1718                                         db->db->error,db->db->arg1,db->db->arg2);
1719                         return 0;
1720                 }
1721
1722         if (db->attributes.unique_subject
1723                 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1724                         LHASH_HASH_FN(index_name_hash),
1725                         LHASH_COMP_FN(index_name_cmp)))
1726                 {
1727                 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
1728                         db->db->error,db->db->arg1,db->db->arg2);
1729                 return 0;
1730                 }
1731         return 1;
1732         }
1733
1734 int save_index(char *dbfile, char *suffix, CA_DB *db)
1735         {
1736         char buf[3][BSIZE];
1737         BIO *out = BIO_new(BIO_s_file());
1738         int j;
1739
1740         if (out == NULL)
1741                 {
1742                 ERR_print_errors(bio_err);
1743                 goto err;
1744                 }
1745
1746         j = strlen(dbfile) + strlen(suffix);
1747         if (j + 6 >= BSIZE)
1748                 {
1749                 BIO_printf(bio_err,"file name too long\n");
1750                 goto err;
1751                 }
1752
1753 #ifndef OPENSSL_SYS_VMS
1754         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1755 #else
1756         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1757 #endif
1758 #ifndef OPENSSL_SYS_VMS
1759         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1760 #else
1761         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1762 #endif
1763 #ifndef OPENSSL_SYS_VMS
1764         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1765 #else
1766         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1767 #endif
1768 #ifdef RL_DEBUG
1769         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1770 #endif
1771         if (BIO_write_filename(out,buf[0]) <= 0)
1772                 {
1773                 perror(dbfile);
1774                 BIO_printf(bio_err,"unable to open '%s'\n", dbfile);
1775                 goto err;
1776                 }
1777         j=TXT_DB_write(out,db->db);
1778         if (j <= 0) goto err;
1779                         
1780         BIO_free(out);
1781
1782         out = BIO_new(BIO_s_file());
1783 #ifdef RL_DEBUG
1784         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1785 #endif
1786         if (BIO_write_filename(out,buf[1]) <= 0)
1787                 {
1788                 perror(buf[2]);
1789                 BIO_printf(bio_err,"unable to open '%s'\n", buf[2]);
1790                 goto err;
1791                 }
1792         BIO_printf(out,"unique_subject = %s\n",
1793                 db->attributes.unique_subject ? "yes" : "no");
1794         BIO_free(out);
1795
1796         return 1;
1797  err:
1798         return 0;
1799         }
1800
1801 int rotate_index(char *dbfile, char *new_suffix, char *old_suffix)
1802         {
1803         char buf[5][BSIZE];
1804         int i,j;
1805         struct stat sb;
1806
1807         i = strlen(dbfile) + strlen(old_suffix);
1808         j = strlen(dbfile) + strlen(new_suffix);
1809         if (i > j) j = i;
1810         if (j + 6 >= BSIZE)
1811                 {
1812                 BIO_printf(bio_err,"file name too long\n");
1813                 goto err;
1814                 }
1815
1816 #ifndef OPENSSL_SYS_VMS
1817         j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1818 #else
1819         j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1820 #endif
1821 #ifndef OPENSSL_SYS_VMS
1822         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s",
1823                 dbfile, new_suffix);
1824 #else
1825         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s",
1826                 dbfile, new_suffix);
1827 #endif
1828 #ifndef OPENSSL_SYS_VMS
1829         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1830                 dbfile, new_suffix);
1831 #else
1832         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1833                 dbfile, new_suffix);
1834 #endif
1835 #ifndef OPENSSL_SYS_VMS
1836         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1837                 dbfile, old_suffix);
1838 #else
1839         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1840                 dbfile, old_suffix);
1841 #endif
1842 #ifndef OPENSSL_SYS_VMS
1843         j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s",
1844                 dbfile, old_suffix);
1845 #else
1846         j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s",
1847                 dbfile, old_suffix);
1848 #endif
1849         if (stat(dbfile,&sb) < 0)
1850                 {
1851                 if (errno != ENOENT 
1852 #ifdef ENOTDIR
1853                         && errno != ENOTDIR)
1854 #endif
1855                         goto err;
1856                 }
1857         else
1858                 {
1859 #ifdef RL_DEBUG
1860                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1861                         dbfile, buf[1]);
1862 #endif
1863                 if (rename(dbfile,buf[1]) < 0)
1864                         {
1865                         BIO_printf(bio_err,
1866                                 "unable to rename %s to %s\n",
1867                                 dbfile, buf[1]);
1868                         perror("reason");
1869                         goto err;
1870                         }
1871                 }
1872 #ifdef RL_DEBUG
1873         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1874                 buf[0],dbfile);
1875 #endif
1876         if (rename(buf[0],dbfile) < 0)
1877                 {
1878                 BIO_printf(bio_err,
1879                         "unable to rename %s to %s\n",
1880                         buf[0],dbfile);
1881                 perror("reason");
1882                 rename(buf[1],dbfile);
1883                 goto err;
1884                 }
1885         if (stat(buf[4],&sb) < 0)
1886                 {
1887                 if (errno != ENOENT 
1888 #ifdef ENOTDIR
1889                         && errno != ENOTDIR)
1890 #endif
1891                         goto err;
1892                 }
1893         else
1894                 {
1895 #ifdef RL_DEBUG
1896                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1897                         buf[4],buf[3]);
1898 #endif
1899                 if (rename(buf[4],buf[3]) < 0)
1900                         {
1901                         BIO_printf(bio_err,
1902                                 "unable to rename %s to %s\n",
1903                                 buf[4], buf[3]);
1904                         perror("reason");
1905                         rename(dbfile,buf[0]);
1906                         rename(buf[1],dbfile);
1907                         goto err;
1908                         }
1909                 }
1910 #ifdef RL_DEBUG
1911         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1912                 buf[2],buf[4]);
1913 #endif
1914         if (rename(buf[2],buf[4]) < 0)
1915                 {
1916                 BIO_printf(bio_err,
1917                         "unable to rename %s to %s\n",
1918                         buf[2],buf[4]);
1919                 perror("reason");
1920                 rename(buf[3],buf[4]);
1921                 rename(dbfile,buf[0]);
1922                 rename(buf[1],dbfile);
1923                 goto err;
1924                 }
1925         return 1;
1926  err:
1927         return 0;
1928         }
1929
1930 void free_index(CA_DB *db)
1931         {
1932         if (db)
1933                 {
1934                 if (db->db) TXT_DB_free(db->db);
1935                 OPENSSL_free(db);
1936                 }
1937         }
1938
1939 int parse_yesno(char *str, int def)
1940         {
1941         int ret = def;
1942         if (str)
1943                 {
1944                 switch (*str)
1945                         {
1946                 case 'f': /* false */
1947                 case 'F': /* FALSE */
1948                 case 'n': /* no */
1949                 case 'N': /* NO */
1950                 case '0': /* 0 */
1951                         ret = 0;
1952                         break;
1953                 case 't': /* true */
1954                 case 'T': /* TRUE */
1955                 case 'y': /* yes */
1956                 case 'Y': /* YES */
1957                 case '1': /* 1 */
1958                         ret = 0;
1959                         break;
1960                 default:
1961                         ret = def;
1962                         break;
1963                         }
1964                 }
1965         return ret;
1966         }
1967
1968 /*
1969  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1970  * where characters may be escaped by \
1971  */
1972 X509_NAME *parse_name(char *subject, long chtype, int multirdn)
1973         {
1974         size_t buflen = strlen(subject)+1; /* to copy the types and values into. due to escaping, the copy can only become shorter */
1975         char *buf = OPENSSL_malloc(buflen);
1976         size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
1977         char **ne_types = OPENSSL_malloc(max_ne * sizeof (char *));
1978         char **ne_values = OPENSSL_malloc(max_ne * sizeof (char *));
1979         int *mval = OPENSSL_malloc (max_ne * sizeof (int));
1980
1981         char *sp = subject, *bp = buf;
1982         int i, ne_num = 0;
1983
1984         X509_NAME *n = NULL;
1985         int nid;
1986
1987         if (!buf || !ne_types || !ne_values)
1988                 {
1989                 BIO_printf(bio_err, "malloc error\n");
1990                 goto error;
1991                 }       
1992
1993         if (*subject != '/')
1994                 {
1995                 BIO_printf(bio_err, "Subject does not start with '/'.\n");
1996                 goto error;
1997                 }
1998         sp++; /* skip leading / */
1999
2000         /* no multivalued RDN by default */
2001         mval[ne_num] = 0;
2002
2003         while (*sp)
2004                 {
2005                 /* collect type */
2006                 ne_types[ne_num] = bp;
2007                 while (*sp)
2008                         {
2009                         if (*sp == '\\') /* is there anything to escape in the type...? */
2010                                 {
2011                                 if (*++sp)
2012                                         *bp++ = *sp++;
2013                                 else    
2014                                         {
2015                                         BIO_printf(bio_err, "escape character at end of string\n");
2016                                         goto error;
2017                                         }
2018                                 }       
2019                         else if (*sp == '=')
2020                                 {
2021                                 sp++;
2022                                 *bp++ = '\0';
2023                                 break;
2024                                 }
2025                         else
2026                                 *bp++ = *sp++;
2027                         }
2028                 if (!*sp)
2029                         {
2030                         BIO_printf(bio_err, "end of string encountered while processing type of subject name element #%d\n", ne_num);
2031                         goto error;
2032                         }
2033                 ne_values[ne_num] = bp;
2034                 while (*sp)
2035                         {
2036                         if (*sp == '\\')
2037                                 {
2038                                 if (*++sp)
2039                                         *bp++ = *sp++;
2040                                 else
2041                                         {
2042                                         BIO_printf(bio_err, "escape character at end of string\n");
2043                                         goto error;
2044                                         }
2045                                 }
2046                         else if (*sp == '/')
2047                                 {
2048                                 sp++;
2049                                 /* no multivalued RDN by default */
2050                                 mval[ne_num+1] = 0;
2051                                 break;
2052                                 }
2053                         else if (*sp == '+' && multirdn)
2054                                 {
2055                                 /* a not escaped + signals a mutlivalued RDN */
2056                                 sp++;
2057                                 mval[ne_num+1] = -1;
2058                                 break;
2059                                 }
2060                         else
2061                                 *bp++ = *sp++;
2062                         }
2063                 *bp++ = '\0';
2064                 ne_num++;
2065                 }       
2066
2067         if (!(n = X509_NAME_new()))
2068                 goto error;
2069
2070         for (i = 0; i < ne_num; i++)
2071                 {
2072                 if ((nid=OBJ_txt2nid(ne_types[i])) == NID_undef)
2073                         {
2074                         BIO_printf(bio_err, "Subject Attribute %s has no known NID, skipped\n", ne_types[i]);
2075                         continue;
2076                         }
2077
2078                 if (!*ne_values[i])
2079                         {
2080                         BIO_printf(bio_err, "No value provided for Subject Attribute %s, skipped\n", ne_types[i]);
2081                         continue;
2082                         }
2083
2084                 if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char*)ne_values[i], -1,-1,mval[i]))
2085                         goto error;
2086                 }
2087
2088         OPENSSL_free(ne_values);
2089         OPENSSL_free(ne_types);
2090         OPENSSL_free(buf);
2091         return n;
2092
2093 error:
2094         X509_NAME_free(n);
2095         if (ne_values)
2096                 OPENSSL_free(ne_values);
2097         if (ne_types)
2098                 OPENSSL_free(ne_types);
2099         if (buf)
2100                 OPENSSL_free(buf);
2101         return NULL;
2102 }
2103
2104 /* This code MUST COME AFTER anything that uses rename() */
2105 #ifdef OPENSSL_SYS_WIN32
2106 int WIN32_rename(char *from, char *to)
2107         {
2108 #ifndef OPENSSL_SYS_WINCE
2109         /* Windows rename gives an error if 'to' exists, so delete it
2110          * first and ignore file not found errror
2111          */
2112         if((remove(to) != 0) && (errno != ENOENT))
2113                 return -1;
2114 #undef rename
2115         return rename(from, to);
2116 #else
2117         /* convert strings to UNICODE */
2118         {
2119         BOOL result = FALSE;
2120         WCHAR* wfrom;
2121         WCHAR* wto;
2122         int i;
2123         wfrom = malloc((strlen(from)+1)*2);
2124         wto = malloc((strlen(to)+1)*2);
2125         if (wfrom != NULL && wto != NULL)
2126                 {
2127                 for (i=0; i<(int)strlen(from)+1; i++)
2128                         wfrom[i] = (short)from[i];
2129                 for (i=0; i<(int)strlen(to)+1; i++)
2130                         wto[i] = (short)to[i];
2131                 result = MoveFile(wfrom, wto);
2132                 }
2133         if (wfrom != NULL)
2134                 free(wfrom);
2135         if (wto != NULL)
2136                 free(wto);
2137         return result;
2138         }
2139 #endif
2140         }
2141 #endif